看到题目大家就知道这个是要做什么了。其实不光是绘图板,还有签名也可以用这个。我们直接上自定义控件。
public class DrawPicture extends View {
private Paint mPaint; //绘制线条的Path
private Path mPath; //记录用户绘制的Path
private Canvas mCanvas; //内存中创建的Canvas
private Bitmap mBitmap; //缓存绘制的内容
private int mLastX;
private int mLastY;
private Context mContext;
public DrawPicture(Context context) {
super(context);
init(context);
}
public DrawPicture(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public DrawPicture(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mContext = context;
mPath = new Path();
mPaint = new Paint(); //初始化画笔
mPaint.setColor(Color.GREEN);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND); //结合处为圆角
mPaint.setStrokeCap(Paint.Cap.ROUND); // 设置转弯处为圆角
mPaint.setStrokeWidth(20); // 设置画笔宽度
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
// 初始化bitmap,Canvas
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
//重写该方法,在这里绘图
@Override
protected void onDraw(Canvas canvas) {
drawPath();
canvas.drawBitmap(mBitmap, 0, 0, null);
}
//绘制线条
private void drawPath() {
mCanvas.drawPath(mPath, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
mLastX = x;
mLastY = y;
mPath.moveTo(mLastX, mLastY);
break;
case MotionEvent.ACTION_MOVE:
int dx = Math.abs(x - mLastX);
int dy = Math.abs(y - mLastY);
if (dx > 3 || dy > 3)
mPath.lineTo(x, y);
mLastX = x;
mLastY = y;
break;
}
invalidate();
return true;
}
public void savePic() {
// 保存绘图为本地图片
try {
mCanvas.save();
mCanvas.restore();
List<String> list = new ArrayList<>();
list.add("pics");
File file = new File(PathGetUtil.getLongwayPath(mContext,list),"pic"+System.currentTimeMillis()+".jpg");// 保存到sdcard根目录下,文件名为share_pic.png
File fileDir = new File(PathGetUtil.getLongwayPath(mContext,list));
if (!fileDir.exists()){
fileDir.mkdirs();
}
if (!file.exists()){
file.createNewFile();
}
FileOutputStream fos = null;
fos = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
保存的方法中涉及一段PathGerUtil.getLongwayPath方法的调用,这个就是组装保存路径的一个方法,大家可以自己写或者用自己的工具。