尝试从Drawable资源创建壁纸时,Android OutOfMemoryError

时间:2014-05-22 13:04:03

标签: android bitmap resources drawable wallpaper

当我尝试从Drawable资源设置壁纸时,我收到了OutOfMemoryError。我该如何解决这个问题?

Context context = v.getContext();
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
try { 
    Drawable drawable = context.getResources().getDrawable(wpResID);
    Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
    wallpaperManager.setBitmap(bitmap);

    bitmap.recycle();
    bitmap = null;
} catch (IOException e) {
    e.printStackTrace();
}

我收到了这个:

05-22 16:03:13.001: E/AndroidRuntime(30942): FATAL EXCEPTION: main
05-22 16:03:13.001: E/AndroidRuntime(30942): java.lang.OutOfMemoryError
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:521)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:374)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.content.res.Resources.loadDrawable(Resources.java:2005)
05-22 16:03:13.001: E/AndroidRuntime(30942):    at android.content.res.Resources.getDrawable(Resources.java:673)

1 个答案:

答案 0 :(得分:0)

首次加载图片时使用BitmapFactory.Options.inSampleSize以使图片尽可能接近目标尺寸,然后使用Bitmap.createScaledBitmap缩放到您想要的确切尺寸。

这个answer中有一些代码。