不可变位图崩溃错误

时间:2012-10-29 10:15:04

标签: android bitmap

java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor
at android.graphics.Canvas.<init>(Canvas.java:127)
at app.test.canvas.StartActivity.applyFrame(StartActivity.java:214)
at app.test.canvas.StartActivity$1.onClick(StartActivity.java:163)
at android.view.View.performClick(View.java:4223)
at android.view.View$PerformClick.run(View.java:17275)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)

我从开发者控制台收到此崩溃错误..我不明白是什么问题..

    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inScaled = true;
    opt.inPurgeable = true;
    opt.inInputShareable = true;
    Bitmap brightBitmap = BitmapFactory.decodeResource(getResources(), position, opt); 
    brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 550, 550, false);
    chosenFrame = brightBitmap;
    Bitmap workingBitmap = Bitmap.createBitmap(chosenFrame);
    workingBitmap = Bitmap.createBitmap(workingBitmap); 
    Canvas c = new Canvas(workingBitmap);

我认为这与此有关吗?

5 个答案:

答案 0 :(得分:188)

您必须将workingBitmap转换为Mutable Bitmap才能在Canvas上进行绘制。 (注意:此方法无助于节省内存,它会使用额外的内存)

Bitmap workingBitmap = Bitmap.createBitmap(chosenFrame);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);

这个答案有助于不浪费记忆力 Convert immutable bitmap to a mutable bitmap

答案 1 :(得分:33)

BitmapFactory.decodeResource()返回位图的不可变副本,您无法绘制到其画布。为了获得它的画布,你需要获得图像位图的可变副本,这可以通过添加单行代码来完成。

opt.inMutable = true;

将该行添加到您的代码中,它应该解决崩溃问题。

答案 2 :(得分:0)

为了最大限度地减少内存使用量,您可以查看这篇文章,直接从资源中转换/解码可变位图:

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

答案 3 :(得分:0)

除非您不想将IMMUTABLE位图设为MUTABLE位图,否则可以通过始终重复使用BITMAP来节省内存

workingBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(workingBitmap);

但是我认为这可能与通过调用

使位图变为可变相同
workingBitmap.isMutable = true

答案 4 :(得分:0)

这也很好,我刚刚对其进行了测试。

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
return BitmapFactory.decodeByteArray(resultDecoded, 0, resultDecoded.length,options);