我可以通过将图像转换为位图并使用以下代码在画布中设置来擦除图像。但我无法设置撤消和重做功能。下面的代码更改了源位图,以便我如何保存路径并执行撤消和重做功能?
public class MyCustomView extends View
{
private Bitmap sourceBitmap;
ImageButton undo, redo;
private Canvas sourceCanvas = new Canvas();
private Paint destPaint = new Paint();
private Path destPath = new Path();
Boolean IsEraserSet = false;
public MyCustomView(Context context, Bitmap rawBitmap)
{
super(context);
//converting drawable resource file into bitmap
// Bitmap rawBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.attire);
//converting bitmap into mutable bitmap
this.undo = undo;
this.redo = redo;
sourceBitmap = Bitmap.createBitmap(rawBitmap.getWidth(), rawBitmap.getHeight(), Bitmap.Config.ARGB_8888);
sourceCanvas.setBitmap(sourceBitmap);
sourceCanvas.drawBitmap(rawBitmap, 0, 0, null);
destPaint.setAlpha(0);
destPaint.setAntiAlias(true);
destPaint.setStyle(Paint.Style.STROKE);
destPaint.setStrokeJoin(Paint.Join.ROUND);
destPaint.setStrokeCap(Paint.Cap.ROUND);
//change this value as per your need
destPaint.setStrokeWidth(50);
destPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
sourceCanvas.drawPath(destPath, destPaint);
canvas.drawBitmap(sourceBitmap, 0, 0, null);
// sourceCanvas.drawPath(destPath, destPaint);
// canvas.drawBitmap(sourceBitmap, 0, 0, null);
}
public void setEraser(Boolean value){
IsEraserSet = value;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if(!IsEraserSet){
return true;
}
float xPos = event.getX();
float yPos = event.getY();
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
destPath.moveTo(xPos, yPos);
break;
case MotionEvent.ACTION_MOVE:
destPath.lineTo(xPos, yPos);
break;
case MotionEvent.ACTION_UP:
upTouch();
break;
}
invalidate();
return true;
}
}
擦除图像后,其外观如下所示。我在删除图像下方添加了背景图像。所以实际上我必须擦除我的顶部图像以显示背景图像。但是我如何添加撤消和重做功能?任何帮助将永远赞赏。
答案 0 :(得分:0)
您应该使用java.util.LinkedList<Path>
而不是Path
。在onDraw
中迭代该列表,并将这些路径绘制到画布上。当用户单击撤消操作时,您只需从列表中删除最后一个路径,而当用户单击重做操作时,您将添加最近删除的路径,这些路径将在备份java.util.Stack<Path>
中。