How to erase previous drawing on Canvas?

49,533

Solution 1

canvas.drawColor(0, Mode.CLEAR);

More info http://developer.android.com/guide/topics/graphics/index.html

Solution 2

canvas.drawColor(0, Mode.CLEAR);

Solution 3

overlayBitmap.eraseColor(Color.TRANSPARENT);

This simply sets an existing Bitmap to all transparent.

I use this to "clear" a Bitmap object that I use to overlay on top of another to show a cropping window.

Solution 4

Just fill in the canvas with a color or image:

canvas.drawColor(Color.BLACK);

If you want to keep certain elements and take certain elements away you can store these in an ArrayList. Then you can add and remove elements from this ArrayList when you want, and then iterate through them in onDraw().

for (Iterator<GraphicObject> it = _graphics.iterator(); it.hasNext();) {
    GraphicObject graphic = (GraphicObject)it.next();
    coords = graphic.getCoordinates();
    canvas.drawCircle(coords.getX(), coords.getY(), (float)coords.getRadius(), paint);
}

Solution 5

Try as below,it can be used to clear the canvas totally.

Declaration should be like this,

ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();
ArrayList<Pair<Path, Paint>> undonePaths = new ArrayList<Pair<Path, Paint>>();

and while clearing use

    undonePaths.clear();
    paths.clear();
    invalidate();
Share:
49,533
springrolls
Author by

springrolls

Updated on October 18, 2020

Comments

  • springrolls
    springrolls over 3 years

    I have a background image (a map) on which I need to regularly draw the you-are-here icon. I use Canvas to draw the icon on top of the map. Assuming that the drawing process is triggered on button click (see code below), how can I erase the previous drawing?

    private void displayUserPos(Point userPos) {
        Bitmap marker = BitmapFactory.decodeResource(getResources(), R.drawable.ic_yah);
        canvas.drawBitmap(marker, (float)userPos.getX(), (float)userPos.getY(), null);
        imgView.setImageBitmap(fmOverlay);
    }
    
  • springrolls
    springrolls almost 13 years
    What if there are other drawings from another button click which I want to keep? Is there a way to somehow get hold of the id?
  • Caner
    Caner almost 13 years
    That is discueessed here: stackoverflow.com/questions/5729377/…
  • springrolls
    springrolls almost 13 years
    Ah, another input. Currently I don't need it yet, but might be helpful later. Thanks! +1
  • Dhruv Mevada
    Dhruv Mevada over 12 years
    This one is very helpful when your canvas needs to be transparent and you can not fill it with white or black or whatever bg color you have.