Efficient way of creating Bitmap out of Drawable from res (BitmapFactory vs Type Casting)

自作多情 提交于 2019-12-10 20:33:23

问题


Which method is more efficient for creating Bitmap out of Drawable from resources?

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

Vs

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

since API 22 above method is deprecated so use following

Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)

回答1:


You can take a look at the source code for Bitmap factory at http://source.android.com specifically the code for decodeResource.

I would reason that using BitmapFactory is preferred but in either case if you are decoding multiple bitmaps then you should call getResources() once and store the result for use as the resources argument for the functions.




回答2:


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

As per the documentation above method is best when we are constructing bitmap from inputStream

Vs

Drawable myDrawable = ContextCompat.getDrawable(context, R.drawable.icon_resource)
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();

This solution is widely used and better in performance as it simply returns the bitmap used by this drawable to render.




回答3:


Both should have similar decoding performance. In fact, initial creation of the Drawable will call Drawable.createFromResourceStream() which calls BitmapFactory.decodeResourceStream().

However, Resources.getDrawable() and Context.getDrawable() use a Drawable cache, so if you are loading the same Bitmap more than once using this API it can skip decoding if the Drawable is in the cache and performance will be better.



来源:https://stackoverflow.com/questions/14840967/efficient-way-of-creating-bitmap-out-of-drawable-from-res-bitmapfactory-vs-type

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