简体   繁体   中英

How to make a canvas white after drawing?

I am drawing on the canvas properly and saving it into a bitmap. However, I want to reset the canvas to white by clicking a button.

Here is my code:

public class Canvas extends View {
    Paint paint;
    Path path;
    boolean cc = false;

public Canvas(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    paint = new Paint();
    path = new Path();
    paint.setAntiAlias(true);
    paint.setColor(Color.RED);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(5f);

}

@Override
protected void onDraw(android.graphics.Canvas canvas) {
    super.onDraw(canvas);
    if (!cc) {
        canvas.drawPath(path, paint);
    }
    else {
        canvas.drawColor(Color.WHITE);
        cc = false;
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float xPos = event.getX();
    float yPos = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            path.moveTo(xPos, yPos);
            return true;
        case MotionEvent.ACTION_MOVE:
            path.lineTo(xPos, yPos);
            break;
        case MotionEvent.ACTION_UP:
            break;
        default:
            return false;
    }
    invalidate();
    return true;
}


public void clear() {
    cc = true;
    invalidate();
}

my clear() function set cc to "true" then invalidate() calls the onDraw() function. But it seems that "cc" is not recognized inside the onDraw() or it has always the same value inside. I tried the path.reset() with no result.

calling clear() does not return any error.

To clear all your canvas use this:

     Paint transparent = new Paint();
     transparent.setAlpha(0);

Update:

Add this line in your button onclick():

canvas.drawColor(Color.WHITE);

And remove it from the draw function.

Seems you'd want the path to get cleared too when your clear() method is called, so do that, then use the fact that the path is empty to clear the canvas.

public void clear() {
    path.reset();
    invalidate();
}

@Override
protected void onDraw(android.graphics.Canvas canvas) {
    super.onDraw(canvas);
    if (path.isEmpty()) {
        canvas.drawColor(Color.WHITE);
    } else {
        canvas.drawPath(path, paint);
    }
}

That entirely eliminates the cc field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM