我想创建一个用户可以设置背景的活动。
不幸的是,当我加载大约7张图像时,图像太大了#39;
它抛出一个异常(Failed to allocate a 74649612 byte allocation with 7804240 free bytes and 7MB until OOM
)。
有没有办法让图像更小?'在Android Studio中,没有在photoshop中缩小它?
@Override
protected void onCreate(Bundle savedInstanceState) {
(...)
ImageView image_1 = (ImageView) findViewById(R.id.image_1);
ImageView image_2 = (ImageView) findViewById(R.id.image_2);
...
image_1.setImageDrawable(getDrawable(R.drawable.background_1));
image_2.setImageDrawable(getDrawable(R.drawable.background_2));
...
我在AndroidManifest.xml中启用了android:largeHeap="true"
。
感谢您的帮助。
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以通过减小可绘制图像的大小来解决此问题,为此您需要先将图像转换为位图,然后使用以下代码来减小位图的大小
public static Bitmap makeBitmap(String fn, int minSideLength, int maxNumOfPixels) {
BitmapFactory.Options options;
try {
options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inJustDecodeBounds = true;
BitmapFactory.BitmapFactory.decodeResource(getResources(), R.drawable.large_icon,options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return null;
}
options.inSampleSize = computeSampleSize(
options, minSideLength, maxNumOfPixels);
options.inJustDecodeBounds = false;
//Log.e(LOG_TAG, "sample size=" + options.inSampleSize);
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeFile(fn, options);
} catch (OutOfMemoryError ex) {
Log.e(LOG_TAG, "Got oom exception ", ex);
return null;
}
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == UNCONSTRAINED) ? 128 :
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == UNCONSTRAINED) &&
(minSideLength == UNCONSTRAINED)) {
return 1;
} else if (minSideLength == UNCONSTRAINED) {
return lowerBound;
} else {
return upperBound;
}
}
答案 2 :(得分:0)
您可以使用Glide加载图像并缩小图像。您可以在Gradle文件中添加它:
repositories {
mavenCentral() // jcenter() works as well because it pulls from Maven Central
}
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:25.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
}
这可能是一种如何使用它的方法:
Glide.with(context)
.load(images.get(position))
.override((int)(thumbnailHeight * IMAGE_SCALE_FACTOR), (int)(thumbnailHeight * IMAGE_SCALE_FACTOR))
.into(imageView);
其中images
是包含图片网址(本地或远程)的ArrayList<String>
,thumbnailHeight
是包含此图片的视图的高度(我还使用了宽度的高度值)使其平方),IMAGE_SCALE_FACTOR
是一个常数,表示你的图像缩小了多少(如果你想要它缩小,只需使用0.1到0.9之间的值)