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

核能气质少年 提交于 2019-11-28 07:19:05

问题


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


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/10847728/how-can-i-get-the-bitmap-of-the-canvas-i-get-in-ondraw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!