Android 如何获得我在 onDraw 中获得的画布的位图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10847728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:12:29  来源:igfitidea点击:

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

androidandroid-canvas

提问by user940016

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

如何从自定义视图的画布创建位图。

采纳答案by kostja

There is no way to extract the Bitmapout 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.

没有办法Bitmap从 a 中提取出来Canvas。您可以访问它的唯一方法是在像这样创建画布时自己传递它new Canvas(myBitmap)并保留引用。

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

EDIT2:请参阅@Alex 评论打击 - 将 a 传递Bitmap给 the的方法Canvas似乎不适用于更新版本的 Android。

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

编辑:如果你没有创建Canvas自己,你可以创建一个屏幕大小Bitmap(你需要或任何大小),然后将它传递给CanvasonDraw这样的电话:canvas.setBitmap(myBitmap)

回答by jcw

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.

虽然getBitmap()画布没有函数,但由于您正在创建自定义视图,因此您可以做的是在视图类中编写这样的函数。

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

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

这将返回视图的位图,但重要的是在所有构造函数中添加它,

this.setDrawingCacheEnabled(true);

Otherwise getDrawingCachewill return null

否则getDrawingCache会返回null

回答by user940016

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.

我发现 Canvas 有一个 setBitmap 函数,但没有 getBitmap 函数。这很奇怪,但无论如何,它使我能够自己创建位图并将其传递给画布,保留参考。

回答by mayank1513

getDrawingCache() is deprecated in API 28.

API 28 中不推荐使用 getDrawingCache()。

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

如果您想在自定义视图之外使用此代码,请使用诸如 viewInstance.getHeight()... viewInstance.draw(canvas) 之类的方法将在位图上绘制视图