Androidは大図、多図ソリューションを効率的にロードし、プログラムメモリのオーバーフローを効果的に回避
2860 ワード
久しぶりにブログを書きましたが、今日はAndroidに大きな図をロードしてメモリオーバーフローを避ける方法について小さな質問を書きます.
キャッシュテクノロジーのコアクラスの使い方は後述するandroid.support.v4.util.LruCacheは画像をロードします.
直接コード:
注意:
プロジェクトディレクトリに直接大きな画像を追加して
mImageView.setImageBitmap(decodeSampledBitmapFromResource( getResources(), R.drawable.a, 100, 100));自分の画像ファイルに変更すればいいです.
キャッシュテクノロジーのコアクラスの使い方は後述するandroid.support.v4.util.LruCacheは画像をロードします.
直接コード:
package com.example.oom_demo1;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;
/**
* Android 、 , OOM
* 1
* **/
public class MainActivity extends Activity {
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imageView);
// 100*100 , ImageView 。
mImageView.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.a, 100, 100));
}
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// inJustDecodeBounds true,
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// inSampleSize
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(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) {
//
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// inSampleSize ,
// 。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
注意:
プロジェクトディレクトリに直接大きな画像を追加して
mImageView.setImageBitmap(decodeSampledBitmapFromResource( getResources(), R.drawable.a, 100, 100));自分の画像ファイルに変更すればいいです.