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

我认为这与此有关?

4

5 回答 5

221

您必须将您的转换workingBitmapMutable BitmapCanvas. (注意:这种方法不利于节省内存,会占用额外的内存)

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

这个答案有助于不浪费内存 将不可变位图转换为可变位图

于 2012-10-29T10:25:41.277 回答
42

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

opt.inMutable = true;

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

于 2013-10-28T22:22:20.353 回答
4

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

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

但是我认为这可能与通过调用使位图可变相同

workingBitmap.isMutable = true
于 2018-02-12T12:28:41.933 回答
4

这也有效,我刚刚测试过。

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
return BitmapFactory.decodeByteArray(resultDecoded, 0, resultDecoded.length,options);
于 2019-11-22T16:01:08.270 回答
1

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

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

于 2013-08-24T10:07:55.233 回答