Android 将资源加载到可变位图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3693060/
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 11:23:59  来源:igfitidea点击:

Loading a resource to a mutable bitmap

androidbitmapout-of-memoryandroid-canvasmutable

提问by stealthcopter

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 drawmethod (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:

我想要做的是在我的draw方法中将位图绘制到主画布之前对其进行一些更改(因为在我的主循环中重复大量绘图似乎很浪费,但它不会改变)。我正在对位图进行以下更改:

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?

哪个避免了这个问题,但它有时会导致 OutOfMemoryExceptions,不知道有什么更好的方法来实现我想要的?

采纳答案by Moss

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

有几种方法可以创建它的副本。这个线程可能对你有帮助:http: //www.anddev.org/how_to_modify_the_image_file-t513.html

回答by KNfLrPn

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

在选项中使用decodeResource(Resources res, int id, BitmapFactory.Options opts)和指定inMutable

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

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

回答by suckgamony

You'd better use RapidDecoder.

你最好使用RapidDecoder

import rapid.decoder.BitmapDecoder;

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

Works for API level 8.

适用于 API 级别 8。

回答by pedjolino

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);

回答by android developer

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

如果您需要处理所有 API 级别,请查看这篇文章:

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

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