Eva*_*que 7 android image out-of-memory
我android:background用来给android布局提供背景图片.
放一些图像后,我得到了这个例外:
08-24 00:40:19.237: E/dalvikvm-heap(8533): Out of memory on a 36000016-byte allocation.
Run Code Online (Sandbox Code Playgroud)
如何在android上使用大图像作为背景?
我可以扩展应用程序堆内存吗?还是不好的事情?
请看一下我的相关问题:
尝试通过保持背景图像尽可能小来最小化应用程序的内存使用量.
这可以通过以下方式完成:
确保您设置为背景的图像正确加载(例如裁剪尺寸,例如适合屏幕尺寸),并在不再需要时立即从内存中释放.
确保在内存中只有一个Bitmap实例.显示后,调用recycle()并将引用设置为null.
这是您加载图片的方式:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Run Code Online (Sandbox Code Playgroud)
感谢Adam Stelmaszczyk为这段美丽的代码.
由于布局中的背景图像,我遇到了类似的问题.图像的内存分配的正常大小应为height*width*4字节(在模式ARGB_8888中,默认模式).
如果在显示活动时看到并分配30MB,则必定存在一些问题.检查是否将背景图像放在drawable文件夹中.在这种情况下,系统必须将该图像缩放到屏幕的特定密度,从而导致大量内存开销.
解决方案:
本答案中的更多信息
希望这可以帮助.
我遇到了同样的问题,并通过以下方法进行了修复:
创建一个drawable-nodpi文件夹,并将背景图像放在其中。
使用毕加索显示图像http://square.github.io/picasso/
使用.fit()和.centerCrop()显示它们,如果需要,毕加索会缩放图像
ImageView ivLogo = (ImageView) findViewById(R.id.ivLogo);
Picasso.with(getApplicationContext())
.load(R.drawable.logo)
.fit()
.centerCrop()
.into(ivLogo);
Run Code Online (Sandbox Code Playgroud)
如果您确实以某种方式用完了内存,毕加索将仅不显示图像,而是给您一个OOM错误。我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
14983 次 |
| 最近记录: |