Question

I was surprised to find that View.onDraw() wipes the canvas before drawing. This isn't what I want. What's a good way to retain the previous drawings so that I only need to draw the changes on top of the previous drawings during each call?

Was it helpful?

Solution 2

I implemented a SurfaceView. Then in I created my own bitmap and canvas that I draw into, to draw to the screen I draw the bitmap to the screen.

For example:

private Canvas myCanvas = null;
private Bitmap myCanvasBitmap = null;
private Matrix identityMatrix;

public mySurfaceCreated(canvasWidth, canvasHeight){
    myCanvasBitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
    myCanvas = new Canvas();
    myCanvas.setBitmap(myCanvasBitmap);
    identityMatrix = new Matrix();
}

public void myDraw(Canvas canvas) {
    // Draw stuff onto myCanvas, NOT the canvas given by the android OS.
    drawStuff(myCanvas);
    // Draw onto the canvas given by the android OS.
    canvas.drawBitmap(myCanvasBitmap, identityMatrix, null);

}

This way I do not need to draw the entire canvas each time, but instead only the needed changes. Note that the canvas created by the OS is still completely redrawn each time.

OTHER TIPS

There are couple of APIs to define dirty rect for view to invalidate:

public void invalidate(Rect dirty)
public void invalidate(int l, int t, int r, int b)

However more likely the View is redrawn all the way, when for example you swipe it, or another View above it in Z order get's invalidated.

You can try to use setDrawingCacheEnabled and if you are doing the drawing yourself, be sure to cache Bitmaps you are drawing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top