【发布时间】:2016-01-17 02:45:07
【问题描述】:
我需要在我的应用中设置背景图片。我使用了一个 imageview 并试图以编程方式设置它的背景。我收到“内存不足错误”。我在 SO 上阅读了其他帖子,并更改了我的代码以仅根据屏幕高度和宽度获取图像。我尝试了其他一些事情,但仍然遇到同样的错误。请帮忙。
谢谢。
@Override
protected void onResume() {
super.onResume();
ivBackground.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.drawable.themes, getDisplayWidth(), getDisplayHeight()));
ivBackground.setScaleType(ScaleType.CENTER_CROP);
}
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 int getDisplayHeight(){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.heightPixels;
}
public int getDisplayWidth(){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
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;
}
xml 布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView android:id="@+id/ivBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainPage"
/>
【问题讨论】:
-
您是尝试在 Asynctask 中并行下载图像还是尝试将图像存储在局部变量中..?
-
为什么要在 onResume() 中设置图片??它根据活动生命周期调用了多次
-
我在 onresume() 中这样做,因为背景图像是根据应用程序的主题设置的。用户可以从应用程序的任何位置选择主题。每当用户回到页面时,我们需要检查主题并相应地设置背景。我没有在上面的代码中粘贴所有细节。如果我在 oncreate 中设置背景图像,则每次用户返回活动时背景都不会改变
-
你应该检查而不是直接设置。
-
@Manmohan。很抱歉没有知道如何使用 check..
标签: android