当我们在App中要加载大图片时,很多时候Logcat会报出OutOfMemoryError的错误,同时会导致App崩溃。这是因为Dalvik虚拟内存小于加载图片需要的内存导致的,这时我们就可以用到Bitmap来缩放图片实现图片的成功加载。直接上代码:
public class MainActivity extends Activity {
private ImageView imageView;
private int windowheight;
private int windowwidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
//获取窗口管理者
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
//获取窗口的高和宽
windowheight = wm.getDefaultDisplay().getHeight();
windowwidth = wm.getDefaultDisplay().getWidth();
/* //没过时的方法 Android3.0开始的
Point outSize = new Point();
wm.getDefaultDisplay().getSize(outSize);
windowwidth=outSize.x;
windowheight=outSize.y;*/
}
//实现Button的点击事件
public void loadImage(View view ){
// Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageState()"+"/***.jpg");
// imageView.setImageBitmap(bitmap);
//图片解析配置
BitmapFactory.Options opts = new Options();
//不解析,只是获取图片的头部信息(宽高)
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(Environment.getExternalStorageState()"+"/***.jpg", opts);
int imageHeight = opts.outHeight;
int imageWidth = opts.outWidth;
// System.out.println("图片宽:" + imageWidth + " 高:" + imageHeight);
//计算缩放比例
int scaleX = imageWidth/windowwidth;
int scaleY = imageHeight/windowheight;
int scale = 1;
if (scaleX > scaleY && scaleY > 1) {
scale = scaleX;
}
if (scaleY > scaleX && scaleX > 1) {
scale = scaleY;
}
//此时准备解析图片
opts.inJustDecodeBounds = false;
//设置缩放比
opts.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageState()"+"/***.jpg",opts);
imageView.setImageBitmap(bitmap);
}
}
xml布局文件里面就一个ImageView和一个Button就不上传了!