【问题标题】:App Crashes when Bitmap Option inSampleSize = 1当位图选项 inSampleSize = 1 时应用程序崩溃
【发布时间】:2013-07-07 07:09:30
【问题描述】:

我正在手机上测试应用程序(尺寸 720x1280)。当我使用 2 的样本大小时,应用程序运行良好。当我尝试使用 1 的样本大小时,应用程序在我绘制图像的行中崩溃(下面提到的代码)。请指出我的代码需要更正的地方。

            canvas.drawBitmap(backgoundImage, 0, 0  , null);  

代码

    public  Bitmap getAssetImage(Context context, String filename) throws IOException {
        AssetManager assets = getApplicationContext().getResources().getAssets();
        InputStream buffer = null;
        try {
            buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

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

        if (tabletSize) {
            Log.i("DragDrop", "am tablet");   
        } else {
            Log.i("DragDrop", "am phone");  
            options.inSampleSize = 1; 
        }


        Bitmap temp = BitmapFactory.decodeStream(buffer, null, options);
        Bitmap finalImage = Bitmap.createScaledBitmap(temp, (int) dWidth, (int) dHeight, true);
        temp.recycle();
        temp=null; 
        return finalImage;   

    }

LogCat

07-07 12:28:14.150: E/AndroidRuntime(7256): FATAL EXCEPTION: Thread-748
07-07 12:28:14.150: E/AndroidRuntime(7256): java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@416ec9f0
07-07 12:28:14.150: E/AndroidRuntime(7256): at android.graphics.Canvas.throwIfRecycled(Canvas.java:1026)
07-07 12:28:14.150: E/AndroidRuntime(7256): at android.graphics.Canvas.drawBitmap(Canvas.java:1065)
07-07 12:28:14.150: E/AndroidRuntime(7256): at com.example.funandlearn.DragDrop$MyBringBackSurface.run(DragDrop.java:640)
07-07 12:28:14.150: E/AndroidRuntime(7256): at java.lang.Thread.run(Thread.java:856)

第 640 行有代码供您参考

            canvas.drawBitmap(backgoundImage, 0, 0  , null);  

【问题讨论】:

  • 它说你已经回收了位图并且你正在使用它。
  • 你的安卓版本是多少?
  • youtube.com/watch?v=_CruQY55HOk。查看此链接了解更多详情

标签: android android-canvas android-image


【解决方案1】:

你有这个

    Bitmap temp = BitmapFactory.decodeStream(buffer, null, options);
    Bitmap finalImage = Bitmap.createScaledBitmap(temp, (int) dWidth, (int) dHeight, true);
    temp.recycle();
    temp=null; 

你的日志猫说

    Canvas: trying to use a recycled bitmap

您应该在不使用时回收位图。

引用自文档

在 Android 2.3.3(API 级别 10)及更低版本上,建议使用 recycle()。

只有当您确定不再使用该位图时,您才应该使用recycle()。如果您调用 recycle() 并稍后尝试绘制位图,您将收到错误:“画布:尝试使用回收的位图”。

在 Android 3.0 及更高版本上管理内存

Android 3.0(API 级别 11)引入了 BitmapFactory.Options.inBitmap 字段。 如果设置了此选项,采用 Options 对象的解码方法将在加载内容时尝试重用现有位图。无需使用recycle

也检查一下

http://developer.android.com/training/displaying-bitmaps/manage-memory.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多