对于加载图片,一般为了尽可能避免OOM都会按照如下做法:
对于图片显示:根据需要显示图片控件的大小对图片进行压缩显示(采样率inSampleSize及矩阵Matrix)。 如果图片数量非常多:则会使用LruCache等缓存机制,将所有图片占据的内容维持在一个范围内。
其实对于图片加载还有种情况,就是单个图片非常巨大,并且还不允许压缩。比如显示:世界地图、清明上河图等。
需要使用Android系统自带的BitmapRegionDecoder。
1 矩阵Matrix 实列代码 ps:使用Matrix进行放大,虽然图像大了,但并没有占用更多的内存。
放大缩小
private Bitmap imageSale(Bitmap b,float salex, float saley){
Matrix matrix = new Matrix();
matrix.postScale(salex,saley);
return Bitmap.createBitmap(b,0,0,b.getWidth(),b.getHeight(),matrix,true);
}
还有利用 Matrix 实现 平移,旋转等等。
2 BitmapRegionDecoder 简单例子。在此基础上可以进行图片的拖拽,放大缩小。
InputStream inputStream = getAssets().open(tangyan.jpg);
//获得图片的宽、高
BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
tmpOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, tmpOptions);
int width = tmpOptions.outWidth;
int height = tmpOptions.outHeight;
//设置显示图片的中心区域
BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
mImageView.setImageBitmap(bitmap);