Search code examples
androidandroid-canvassurfaceviewandroid-bitmap

getting a part of a Canvas as a Bitmap


I'm trying to get a part of SurfaceView's canvas and save it as a Bitmap.
Every answer i've seen about it was creating a new Canvas and passing it your Bitmap to the constructor.

Because I am using SurfaceView, I am getting my canvas using the SurfaceHodler with mSurfaceHolder.lockCanvas(); thus i can't creat a new Canvas with my Bitmap.

How can I get a part of my canvas to a Bitmap without crating a new canvas?


Solution

  • A Canvas is a rendering interface. You can't get part of it, or all of it, because it's just the interface. The pixels are drawn to a Bitmap or to the Surface, so if you want them you either have to read them back, or draw them again.

    There's no way to retrieve pixels from a Surface -- it's the producer side of a producer-consumer pair. The easiest thing to do is to repeat your drawing commands with a new Canvas that is backed by a Bitmap.

    See also this answer.