简体   繁体   English

绘图后如何使画布变白?

[英]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.我的 clear() 函数将 cc 设置为“true”,然后 invalidate() 调用 onDraw() 函数。 But it seems that "cc" is not recognized inside the onDraw() or it has always the same value inside.但似乎在 onDraw() 内部无法识别“cc”,或者它内部始终具有相同的值。 I tried the path.reset() with no result.我尝试了 path.reset() 没有结果。

calling clear() does not return any error.调用 clear() 不会返回任何错误。

To clear all your canvas use this:要清除所有画布,请使用以下命令:

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

Update:更新:

Add this line in your button onclick():在您的按钮 onclick() 中添加这一行:

canvas.drawColor(Color.WHITE); canvas.drawColor(Color.WHITE);

And remove it from the draw function.并将其从 draw 函数中删除。

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.似乎您希望在调用clear()方法时也清除path ,所以这样做,然后使用path为空的事实来清除画布。

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.这完全消除了cc字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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