Clear The Canvas Area
I have made a custom view which is refereed from xml layout. I added a button for clearing the view. Now I want to clear the canvas area upon clicking. I added an onClick event in
Solution 1:
What you need to do is access the canvas in the onDraw method.
So if you use a global variable, in your button click method, and set it to true. In OnDraw you can check its status and clear canvas if necessary. (Then set it back to false so it doesnt do it every time).
See code below for usage.
public Boolean clearCanvas = false;
protectedvoidonDraw(Canvas canvas) {
super.onDraw(canvas);
if(clearCanvas)
{ // Choose the colour you want to clear with.
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
clearCanvas = false;
}
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
returntrue;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do break;
default:
returnfalse;
}
// Schedules a repaint.
invalidate();
returntrue;
}
// this is the method which will be invoked from main activity class for clearing whatever //is in the view/canvas publicvoidclearCanvas(){
//canvas.drawColor(0, Mode.CLEAR);
clearCanvas = true;
invalidate();
}
}
EDIT: Looking at your new code I see a few problems.
I think it revoles around the fact you are not clearing the correct view.
First off, obtain the instance of the existing view. Then you can clear it. Rather than the wrong non existing instance of it.
CustomViewcv= (CustomView)findViewById(R.id.customView);
cv.clearCanvas();
Try invalidate();
else postInvalidate();
One should work.
postInvalidate()
is for when you are running on a non UI Thread.
Post a Comment for "Clear The Canvas Area"