How can I get the bitmap of the canvas I get in on

2020-02-13 06:47发布

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

4条回答
家丑人穷心不美
2楼-- · 2020-02-13 07:32

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

查看更多
ゆ 、 Hurt°
3楼-- · 2020-02-13 07:37

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

查看更多
够拽才男人
4楼-- · 2020-02-13 07:50

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.

查看更多
Root(大扎)
5楼-- · 2020-02-13 07:54

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

查看更多
登录 后发表回答