Loading a resource to a mutable bitmap

允我心安 提交于 2019-11-26 22:53:36

问题


I am loading a bitmap from a resource like so:

 Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image);

What I want to do is make some changes to the bitmap before It gets drawn to the main canvas in my draw method (As it would seem wasteful to repeat lots of drawing in my main loop when it isn't going to change). I am making the changes to the bitmap with the following:

Canvas c = new Canvas(mBackground);
c.drawARGB(...); // etc

So naturally I get an exception

java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor

So to avoid that I made a copy of the bitmap so that it is mutable

Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image).copy(Bitmap.Config.ARGB_8888, true);

Which avoid the problem however it sometimes causes OutOfMemoryExceptions, do know any better ways of achieving what I want?


回答1:


There are several ways to create a copy of it. This thread might help you: http://www.anddev.org/how_to_modify_the_image_file-t513.html




回答2:


Use decodeResource(Resources res, int id, BitmapFactory.Options opts) and specify inMutable in the options.

http://developer.android.com/reference/android/graphics/BitmapFactory.html




回答3:


You'd better use RapidDecoder.

import rapid.decoder.BitmapDecoder;

Bitmap mBackground = BitmapDecoder.from(res, R.drawable.image)
        .mutable().decode();

Works for API level 8.




回答4:


in case you need to handle all API levels, check out this post:

https://stackoverflow.com/a/16314940/878126




回答5:


Instad of yours:

Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image);

Use:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;

Bitmap mBackground = BitmapFactory.decodeResource(res,R.drawable.image, options);


来源:https://stackoverflow.com/questions/3693060/loading-a-resource-to-a-mutable-bitmap

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