Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the bitmap of the canvas I get in onDraw?

How can I create the bitmap from the canvas of custom view.

like image 270
user940016 Avatar asked Jun 01 '12 09:06

user940016


People also ask

How to get Bitmap from canvas?

There is no way to extract the Bitmap out of a Canvas . The only way you can access it is to pass it yourself when creating the canvas like this new Canvas(myBitmap) and keep the reference.

Is canvas a Bitmap?

Bitmap are close to OS, it is an array of data describing pixels. Canvas is close to what human can see in life like a painting canvas where you can draw a circle or a point, but it doesn't save how this circle pixels will represent in memory (that does bitmap). So, Canvas goes along with Bitmap.

What is onDraw method?

Override onDraw() The parameter to onDraw() is a Canvas object that the view can use to draw itself. The Canvas class defines methods for drawing text, lines, bitmaps, and many other graphics primitives. You can use these methods in onDraw() to create your custom user interface (UI).

What is canvas in Android?

The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).


3 Answers

While there is no getBitmap() function for a canvas, since you are making a custom view, what you can do instead is write a function like this inside your view class.

public Bitmap get(){    return this.getDrawingCache(); } 

This returns the Bitmap of the view, but it is important that in all your constructors you add this,

this.setDrawingCacheEnabled(true); 

Otherwise getDrawingCache will return null

like image 176
jcw Avatar answered Oct 18 '22 23:10

jcw


There is no way to extract the Bitmap out of a Canvas. The only way you can access it is to pass it yourself when creating the canvas like this new Canvas(myBitmap) and keep the reference.

EDIT2: see @Alex comment blow - the approach of passing a Bitmap to the Canvas does not seem to work for more recent versions of Android.

EDIT : If you don't create the Canvas yourself, you could create a screen-sized Bitmap (or whatever size you need) and then pass it to the Canvas in onDraw calls like this: canvas.setBitmap(myBitmap).

like image 25
kostja Avatar answered Oct 18 '22 23:10

kostja


I found out that Canvas has a setBitmap function, but not a getBitmap one. It's strange, but anyway, it enables me to create the bitmap myself and pass it to the canvas, retaining the reference.

like image 40
user940016 Avatar answered Oct 18 '22 23:10

user940016