gpt4 book ai didi

android - 在 ImageView 中使用位图时出现 OutOfMemory 问题

转载 作者:行者123 更新时间:2023-11-29 01:46:39 25 4
gpt4 key购买 nike

我的 android 应用程序中有超过 8 个 Activity ,所有屏幕都有很多 imageView,它们将使用位图图像呈现

当我们打开所有屏幕( Activity )时,它会正常工作几次,然后会出现内存不足错误,应用程序崩溃

这是我的代码如何显示图像,请建议如何避免这个/管理这个内存不足的问题

XML:

<?xml version="1.0" encoding="utf-8"?>    
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/img_background">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:id="@+id/artifactImage"
android:onClick="displayFullScreenImage"/>

</LinearLayout>

Activity :

ImageView artifact_Image = (ImageView) gridView.findViewById(R.id.artifactImage);     
artifact_Image.setImageBitmap(artifactImages[position]);
artifact_Image.setDrawingCacheEnabled(false);

最佳答案

可能您显示的图像占用了整个内存空间,这就是您收到此错误的原因。您可能想查看有关如何显示位图的文档:

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

在您的情况下,您应该加载图像的缩小版本。查看此链接以获取示例代码:

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

为了方便起见,我也将示例代码复制到这里。

计算样本量:

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) {

final int halfHeight = height / 2;
final int halfWidth = width / 2;

// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}

return inSampleSize;
}

解码位图:

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

最后设置缩放后的位图

mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

关于android - 在 ImageView 中使用位图时出现 OutOfMemory 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21037135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com