在安卓这样内存有限的平台上,内存有限,因此在加载图片时,我们按照我们需要显示的大小对原始图片再设置所需要大小。也可以根据我们所能够使用的内存大小来对图片进行解码,可以利用BitmapFactory的Options来达到这一目的:
private static int calulaeInSampleSize(BitmapFactory.Options options, int reqWidth,
int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if(height > reqHeight || width > reqWidth) {
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(
Resources paramResources, int paramInt1, int paramInt2,
int paramInt3) {
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inJustDecodeBounds = true;
BitmapFactory.decodeResource(paramResources, paramInt1, localOptions);
localOptions.outWidth = paramInt2;
localOptions.outHeight = paramInt3;
localOptions.inSampleSize = 1;
localOptions.inJustDecodeBounds = false;
localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeResource(paramResources, paramInt1,
localOptions);
}
举个例子:
用这个方法来显示一张大墙纸按照自己的分辨率
private Bitmap mBackgroundBitmap;
private Bitmap mBackBitmap;
try {
if (mBackBitmap == null) {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int winWidht = displayMetrics.widthPixels;
int winHeight = displayMetrics.heightPixels;
mBackBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
if(mBackgroundBitmap == null ) {
mBackgroundBitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.default_wallpaper, winWidht, winHeight);
}
Canvas c = new Canvas();
c.setBitmap(mBackBitmap);
Rect src = new Rect(0, winHeight - h, winWidht, winHeight);
Rect dst = new Rect(0, 0, w, h);
c.drawBitmap(mBackgroundBitmap, src, dst, null);
}
mRender.setmBackBitmap(mBackBitmap);
mRender.init(mRs, mContext.getResources(), false);
mRender.start();
} catch (OutOfMemoryError e){
mBackBitmap = null;
}
当然调用这个以后要注意处理Bitmap
mBackgroundBitmap.recycle();
mBackgroundBitmap = null;
以避免空指针和溢出内存等问题。