【问题标题】:Android Out of memory loading bitmapsAndroid 内存不足加载位图
【发布时间】:2012-10-10 07:50:36
【问题描述】:

我有一个 android 游戏,可以加载 6 张图像,总共 300kb。我已经阅读并实现了这篇文章http://developer.android.com/training/displaying-bitmaps/load-bitmap.html,虽然它有点帮助,但它并没有 100% 解决我的问题。

当游戏第一次加载时,它运行良好。没有错误或任何东西。然后当您关闭游戏或按下主屏幕按钮并稍后返回游戏时,它会出现内存不足错误,但只是有时。在我的简历中,我只是开始备份游戏线程。我没有加载任何图像或类似的东西。我肯定不能拥有加载 6 张或更多图片的唯一游戏吗?

我的简历

    @Override
    protected void onResume(){
        try{
            game.setIsPaused(false);
            game.startSounds();
            game.threadStart();
        super.onResume();
    }

在自己的线程中加载我的图像

bg = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.bg, context, options), imgPercentWidth, imgPercentHeight);
overlay = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.overlay, context, options), imgPercentWidth, imgPercentHeight);
reel = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.reels, context, options), imgPercentWidth, imgPercentHeight);
payOutBG = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.payout, context, options), imgPercentWidth, imgPercentHeight);
achievement = bt.resizeBitmapPercent(bt.createBitmap(R.drawable.achievement, context, options), imgPercentWidth, imgPercentHeight);

调整位图大小和创建位图的方法

public Bitmap createBitmap(int id, Context context, BitmapFactory.Options options){
    return BitmapFactory.decodeResource(context.getResources(), id, options);
}
public Bitmap resizeBitmapPercent(Bitmap bitmap, float w, float h){       
    float newWidth = bitmap.getWidth()*w;
    float newHeight = bitmap.getHeight()*h;
    float scaleWidth = (float) newWidth / bitmap.getWidth();
    float scaleHeight = (float) newHeight / bitmap.getHeight();
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    return Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

【问题讨论】:

标签: android memory-management bitmap out-of-memory


【解决方案1】:

关闭游戏后总是尝试清空位图

我通常使用这个代码

bmp.recycle();
bmp = null;
System.runFinalization();
Runtime.getRuntime().gc();
System.gc();

它会回收位图并使用垃圾收集器

【讨论】:

  • 游戏何时关闭或暂停?我在游戏关闭时回收图像,但我读到你不应该在暂停时回收图像是真的吗?
  • 是的,游戏结束后。如果你想再次使用它,不要回收它,当你使用它时回收它
  • 我继续添加了这个,但我认为它不会解决我的问题。我的问题是当用户点击主页按钮并将应用程序置于后台时引起的。然后他们点击图标,游戏回到前面。然后我得到一个内存不足的错误。
【解决方案2】:

我可以通过将我所有的非透明图像从 png 转换为 jpeg 并在 photoshop 中将它们的质量降低到 60 来解决这个问题。它将我的总图像大小从 300kb 降低到 100ish kb。我担心质量下降看起来很糟糕,但您无法判断智能手机或平板电脑的质量下降。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-21
    • 2013-05-08
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    相关资源
    最近更新 更多