从res中创建位图的高效方法(BitmapFactory与类型转换)

6
哪种方法更有效创建从资源中的Drawable生成Bitmap?
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.icon_resource);

Vs

Drawable myDrawable = getResources().getDrawable(R.drawable.icon_resource);
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();

自API 22以上版本,上述方法已被弃用,请使用以下方法

Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
4个回答

1
你可以查看Bitmap factory的源代码,链接为http://source.android.com,特别是decodeResource的代码。
我认为使用BitmapFactory是首选,但无论哪种情况,如果你要解码多个位图,则应该调用getResources()一次并将结果存储为函数的资源参数以供使用。

嗨Merlin,我看了一下“decodeResource”的源代码,目前我只能理解它有助于根据“Option参数”创建缩放位图,而在我的情况下该参数为空。我仍然认为类型转换是更好的选择,因为它不涉及任何编码/解码。如果我错了,请纠正我。 - AndyW

0
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.icon_resource);

根据上面的文档,当我们从输入流构建位图时,上述方法是最佳选择。
对比。
Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();

这种解决方案被广泛使用,性能更好,因为它只是返回此可绘制对象用于渲染的位图。


0

两者的解码性能应该相似。实际上,Drawable 的初始创建将调用 Drawable.createFromResourceStream(),该方法又会调用 BitmapFactory.decodeResourceStream()

然而,Resources.getDrawable()Context.getDrawable() 使用 Drawable缓存,因此如果您使用此 API 加载同一位图超过一次,则可以跳过解码(如果 Drawable 在缓存中),从而提高性能。


0

这两种方法都非常高效,但在低端设备上可能运行得更慢。

您只需要针对每个ResId调用一次decodeResource()(甚至可能在单独的线程上),然后将加载的资源存储在内存中以供后续调用,以防止臭名昭著的ANR(应用程序无响应)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接