集册 Android 百战经典 百战经典第八战-BitmapFactory.Options对资源图片进行缩放

百战经典第八战-BitmapFactory.Options对资源图片进行缩放

欢马劈雪     最近更新时间:2020-08-04 05:37:59

92

We all know,编写的应用程序都是有一定内存限制的,程序占用了过高的内存就容易出现OOM(OutOfMemory)异常。因此在展示高分辨率图片的时候,最好先将图片进行压缩,压缩后的图片大小应该和用来展示它的控件大小相近,这样可以协调显示效果和内存占用。

BitmapFactory.Options这个类,有一个字段叫做 inJustDecodeBounds 。SDK中对这个成员的说明是这样的: If set to true, the decoder will return null (no bitmap), but the out… 也就是说,如果我们把它设为true,那么BitmapFactory.decodeFile(String path, Options opt)并不会真的返回一个Bitmap给你,它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了。

下面通过具体实例来展示怎么实现缩略图。

1.布局文件:

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical" >  
    <ImageView  
        android:id="@+id/imageView1"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:src="@drawable/mei" />  
    <ImageView  
        android:id="@+id/imageView2"  
        android:layout_width="wrap_content"  
        android:layout_below="@+id/imageView1"  
        android:layout_height="wrap_content"  
        android:layout_marginTop="10dp"  
        android:src="@drawable/mei" />  
</RelativeLayout>  

2.MainActivity.java代码如下:

展开阅读全文