加载原理:Android 机默认为每个应用分配的堆内存是16M,当在界面显示图片时,需要的内存空间不是按图片的实际大小来计算的,而是按像素点的多少乘以每个像素点占用的空间大小来计算的。
所以一不小心就OOM(OutOfMemoryError)内存溢出了,
举个例子:一张图片ps过后像素为 3648*2736不变,内存被转成1M,但是实际上加载时像素为3648*2736=9980928,和内存没关系
在Android中一般为<p> ARGB_8888 : 4bytes 每个像素占据4 个字节
<span style="font-family: monospace; white-space: pre; background-color: rgb(240, 240, 240);"> =9980928 *2bytes</span><span style="font-family: monospace; white-space: pre; background-color: rgb(240, 240, 240);">=38M>16M</span></p><p><span style="font-family: monospace; white-space: pre; background-color: rgb(240, 240, 240);">所以加载图片是 实际上是创建的一个视图 并没有使用原图</span></p><p><span style="font-family: monospace; white-space: pre; background-color: rgb(240, 240, 240);">代码实现:=19M>16M
</span></p><p align="left"><pre name="code" class="html">protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void loadImage(View view) {
try {
WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
int screenWidth =wm.getDefaultDisplay().getWidth();
int screenHeight =wm.getDefaultDisplay().getHeight();
System.out.println("屏幕width:" + screenWidth);
System.out.println("屏幕height:" + screenHeight);
//创建一个可选项对象,该对象用于配置图片的处理参数
Options opts = new Options();
// 将该参数设置为true 则加载器不加载图片, 而是把图片的out(宽和高)的字段信息取出来
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile("mnt/sdcard/big.jpg", opts);
int outWidth = opts.outWidth;
int outHeight = opts.outHeight;
// 计算缩放比例
int widthScale = outWidth /screenWidth;
int heightScale = outHeight/ screenHeight;
//计算出最大的比例
int scale = widthScale >heightScale ? widthScale : heightScale;
System.out.println("scale:"+scale);
// 使用缩放比例进行缩放加载图片
opts.inJustDecodeBounds = false;// 加载器就会返回图片了
opts.inSampleSize = scale;
Bitmap bitmap = BitmapFactory
.decodeFile("mnt/sdcard/big.jpg", opts);
//显示在屏幕上
iv.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
=19M>16M