在我的Android应用程序中,为了避免OOM(位图内存不足错误),我正在缩放并从assets文件夹加载图像。我在res \ drawable-hdpi文件夹中有一些我的图像。有没有我能像我对资产文件夹中的图像那样缩放和加载它?
@SuppressLint("NewApi")
public Drawable getAssetImage(String filename) throws IOException {
int dWidth,dHeight;
Display display = getWindowManager().getDefaultDisplay();
if ( Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13 ) {
dWidth = display.getWidth();
dHeight = display.getHeight();
} else {
Point size = new Point();
display.getSize(size);
dWidth = size.x;
dHeight = size.y;
}
AssetManager assets = getApplicationContext().getResources().getAssets();
InputStream buffer = null;
try {
buffer = new BufferedInputStream((assets.open(filename + ".png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
if (tabletSize) {
} else {
int tempSampleSize = calculateInSampleSize(options, (int)dWidth, (int)dHeight);
Log.i("ClassicalMemoryGame", "dWidth " + dWidth );
Log.i("ClassicalMemoryGame", "dHeight " + dHeight );
Log.i("ClassicalMemoryGame", "sample size - " + tempSampleSize );
if (tempSampleSize > 1) {
options.inSampleSize = tempSampleSize;
}
}
options.inJustDecodeBounds = false;
Bitmap temp = BitmapFactory.decodeStream(buffer, null, options);
Bitmap finalImage = Bitmap.createScaledBitmap(temp, (int) dWidth, (int) dHeight, true);
Drawable d = new BitmapDrawable(getResources(),finalImage);
return d;
}
答案 0 :(得分:0)
您可以使用以下方法:
public static Bitmap decodeScaledSampleBitmap(Resources res,
int resourceId,int width, int height)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resourceId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options,
width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap b = Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(res, resourceId, options),
width, height, true);
return b;
}