27

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

Deepak Swami
  • 3,838
  • 1
  • 31
  • 46
user940016
  • 2,878
  • 7
  • 35
  • 56
  • 5
    I just don't get why it was voted down... – user940016 Oct 19 '12 at 16:47
  • 1
    @user940016 - your question shows no research, or any attempt to solve the problem yourself. read this for more information: http://stackoverflow.com/questions/how-to-ask – katzenhut May 22 '14 at 10:38

4 Answers4

37

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

jcw
  • 5,132
  • 7
  • 45
  • 54
15

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).

kostja
  • 60,521
  • 48
  • 179
  • 224
  • But if I use onDraw, I get a canvas rather than creating it myself, so I don't have a reference to the bitmap... – user940016 Jun 01 '12 at 10:00
  • 2
    If you don't create the `Canvas` yourself, you can not interact with its `Bitmap`. Calling `canvas.setBitmap()` in `onDraw()` causes `UnsupportedOperationException` – Alex Aug 21 '15 at 09:35
  • this may have changed in the last 3 years. The last time I tried was with 2.3 :) What is the version you have tried it with? And thanks for noticing, I will edit accordingly. – kostja Aug 23 '15 at 07:43
  • This approach won't work with a hardware accelerated canvas. – Johann May 04 '21 at 17:03
2

getDrawingCache() is deprecated in API 28.

So now you may use following code inside your custom view

Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
draw(canvas);
// return bitmap; -- this is the bitmap you need

If you want to use this code outside your cusom view use methods like viewInstance.getHeight()... viewInstance.draw(canvas) will draw the view on the bitmap

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
1

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.

user940016
  • 2,878
  • 7
  • 35
  • 56