实现功能:导入背景图片,感知用户的touch操作,实现在背景图片上的涂鸦功能。将canvas分为两层,一层时背景图片,一层是用户涂鸦的图片,将两层叠加返回新的view,并存储。
public class HandWriteView extends View
{
Paint paint = null;
private Bitmap drawingBitmap = null;
Bitmap afterDrawingBitmap = null;
private Bitmap originalBitmap = null;
private float clickX = 0,clickY = 0;
private float startX = 0,startY = 0;
private boolean isMove = true;
private boolean isClear = false;
public int color = Color.RED;
public float strokeWidth = 6.0f;
public HandWriteView(Context context, Bitmap bitmap)
{
super(context);
drawingBitmap =bitmap;
afterDrawingBitmap = Bitmap.createBitmap(bitmap);
}
public void clear(){
isClear = true;
originalBitmap = Bitmap.createBitmap(drawingBitmap);
invalidate();
}
public void setstyle(float strokeWidth){
this.strokeWidth = strokeWidth;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawBitmap(HandWriting(afterDrawingBitmap), 0, 0,null);
}
public Bitmap HandWriting(Bitmap dwawingBitmap)
{
Canvas canvas = null;
if(isClear){
canvas = new Canvas(originalBitmap);
}
else{
canvas = new Canvas(dwawingBitmap);
}
paint = new Paint();
paint.setStyle(Style.STROKE);
paint.setAntiAlias(true);
paint.setColor(color);
paint.setStrokeWidth(strokeWidth);
if(isMove){
canvas.drawLine(startX, startY, clickX, clickY, paint);
}
startX = clickX;
startY = clickY;
if(isClear){
return originalBitmap;
}
return dwawingBitmap;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
clickX = event.getX();
clickY = event.getY();
if(event.getAction() == MotionEvent.ACTION_DOWN){
startX=event.getX();
startY=event.getY();
isMove = false;
invalidate();
return true;
}
else if(event.getAction() == MotionEvent.ACTION_MOVE){
isMove = true;
invalidate();
return true;
}
return super.onTouchEvent(event);
}
}
注意:在onTouchEvent中必须试试更改clickX和clickY,才能让涂鸦有更好的体验
clickX = event.getX();
clickY = event.getY();