从 res (BitmapFactory vs Type Casting) 从 Drawable 创建位图的有效方法

And*_*dyW 5 android bitmap bitmapfactory android-resources android-drawable

哪种方法更有效地从资源中从 Drawable 创建 Bitmap?

Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.icon_resource);
Run Code Online (Sandbox Code Playgroud)

对比

Drawable myDrawable = getResources().getDrawable(R.drawable.icon_resource);
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();
Run Code Online (Sandbox Code Playgroud)

由于 API 22 以上方法已弃用,因此请使用以下方法

Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
Run Code Online (Sandbox Code Playgroud)

Mer*_*lin 1

您可以在http://source.android.com查看位图工厂的源代码, 特别是decodeResource 的代码。

我认为使用 BitmapFactory 是首选,但在任何一种情况下,如果您要解码多个位图,那么您应该调用 getResources() 一次并存储结果以用作函数的资源参数。