I have an drawing app for Android and I am currently trying to add a real eraser to it. Before, I had just used white paint for an eraser, but that won\'t do anymore since n
Can you comment canvas.drawPath(mPreviewPath, mPaint) line and see if it works:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
//canvas.drawPath(mPreviewPath, mPaint);
}
None of the above answers, worked properly for me. After some hit and trial, and some logics as well, solved it, check the ACTION_MOVE
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isEdited = true;
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
if(isEraser) {
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
drawPath.moveTo(touchX, touchY);
} else {
drawPath.lineTo(touchX, touchY);
}
break;
case MotionEvent.ACTION_UP:
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
and this
public void setEraser(boolean isEraser) {
this.isEraser = isEraser;
if (isEraser) {
drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
} else {
drawPaint.setXfermode(null);
}
}
I could suggest you to read the official sample of FingerPaint.java
It exactly matches what you are trying to achieve here.
To not show the trail when you erase content, take a look at the onDraw()
method and the eraserMode
variable:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
if (!eraserMode) {
canvas.drawPath(mPath, mPaint);
}
}
boolean eraserMode = false;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
eraserMode = false;
mPaint.setXfermode(null);
mPaint.setAlpha(0xFF);
switch (item.getItemId()) {
/*...*/
case ERASE_MENU_ID:
// Add this line
eraserMode = true;
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
return true;
/*...*/
}
return super.onOptionsItemSelected(item);
}
when you want make eraser set painting color same as color of canvas not transparent in real life. in android we set set paint color as theme color of canvas mostly either white or black.
mColor = Color.BLACK;
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(mBrushSize);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setAntiAlias(true);
People Still looking for a shorter way to remove that black line while erasing. Just addsetLayerType(View.LAYER_TYPE_SOFTWARE, drawPaint);
this line to the constructor and here you go. Cheers!