Skip to content Skip to sidebar Skip to footer

How To Draw To Canvas From Surfaceview?

I'm trying to do simple painter. The problem that it looks like Android has three independent Canvas and give me it for drawing sequentially. I made UI with SurfaceView, took Hold

Solution 1:

The Canvas that Surface.lockCanvas gives you is not persistent. The moment you call unlockCanvasAndPost, the contents of the surface buffer are pushed out to the screen. Every time you call lockCanvas you need to redraw the picture from scratch.

If you want to update the canvas incrementally, you should keep an "off-screen" canvas backed by a Bitmap that you update in response to user actions. Then paint the bitmap to the Surface canvas.

privatevoidpaintStartDot(float x, float y) {
    if (mBitmap == null) return;  // not ready yetCanvascanvas=newCanvas(mBitmap);
    canvas.drawPoint(x, y, drawPaint);

    // draw the bitmap to surface 
    canvas = surface.lockCanvas(null);
    canvas.drawBitmap(mBitmap, 0, 0, null);
    surface.unlockCanvasAndPost(canvas);
}

@OverridepublicvoidsurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // good place to create the Bitmap
    mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config. ARGB_8888);
    // also here we need to transform the old bitmap to new one
}

I'm not sure if you really need a SurfaceView. You could just extend the View and override its View.onDraw method. In that case, call view.invalidate() to indicate it needs to be redrawn.

See also: Android View.onDraw() always has a clean Canvas

Post a Comment for "How To Draw To Canvas From Surfaceview?"