通过android自定义view 自定义手写签名栏,保存在本地相册
package com.exampl.eventdemo.widgets;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Path;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class SignPadView extends View { /** * 记录手指的轨迹信息 */ PRivate Path mPath; /** * 绘制样式 */ private Paint mPaint; /** * 用于存储Canvas中的图像 */ private Bitmap mBitmap; /** * 封装Bitmap, 绘制的内容自动在Bitmap中显示 */ private Canvas mBufferedCanvas; public SignPadView(Context context) { this(context, null); } public SignPadView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } private void init(Context context, AttributeSet attributeSet){ mPath = new Path(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Paint.Style.STROKE); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if(mBufferedCanvas != null){ mBufferedCanvas = null; } if(mBitmap != null){ mBitmap.recycle(); } // 1. 创建宽高指定的Bitmap mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); // 2. 绘制缓冲区 mBufferedCanvas = new Canvas(mBitmap); } /** * 控件自身通过 Canvas 参数,显示在屏幕上 * @param canvas */ @Override protected void onDraw(Canvas canvas) { mBufferedCanvas.drawColor(Color.WHITE); // 双缓冲技术 // 1. 绘制图片 mBufferedCanvas.drawPath(mPath, mPaint); // 2. 绘制屏幕 canvas.drawBitmap(mBitmap, 0, 0, mPaint);// canvas.drawPath(mPath, mPaint); } public void saveFile(String path){ if (mBitmap != null && path != null) { File file = new File(path); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { FileOutputStream fout = new FileOutputStream(file); mBitmap.compress(Bitmap.CompressFormat.JPEG, 30, fout); fout.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); // 凡是在控件内部的各种事件操作,直接使用相对坐标 float ex = event.getX(); float ey = event.getY(); switch (action){ case MotionEvent.ACTION_DOWN: mPath.moveTo(ex, ey); // 指定当前新的线段的起始位置 break; case MotionEvent.ACTION_MOVE: mPath.lineTo(ex, ey); // 当前线段的点与指定的点之间连接一条很小的线段 break; case MotionEvent.ACTION_UP: break; } // 刷新当前控件,让Android系统自动显示内容 调用 onDraw方法 invalidate(); return true; }}新闻热点
疑难解答