四步实现根据View大小压缩加载Bitmap

根据View大小压缩加载Bitmap:
1.将BitmapFactory.Options的inJustDecodeBounds设置为:true,并加载图片
2.从BitmapFactory.Options取出图片的原始尺寸信息,它们应对与outWidth和outHeigth参数
3.根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize
4.将BitmapFactory.Options的inJustDecodeBounds参数设置成false,然后重新加载图片

*注意:这里inJustDecodeBounds设置为:true时,BitmapFactory并不会真正的去加载Bitmap,只是去解析Bitmap的宽高信息,所以这个操作是轻量级的
根据上面4步流程来实现,就产生了如下代码:

package com.example.administrator.myapplication.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * Created by Administrator on 2016/11/14 0014.
 */

public class BitmapUtil {
    public static Bitmap decodeSampledbitmapFromResource(Resources resources, int resID, int reqWidth, int reqHeight) {
        final BitmapFactory.Options option = new BitmapFactory.Options();
        //设置inJustDecodeBounds为:ture,预先加载Bitmap的宽高参数
        option.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resID, option);
        //计算图片的采样率
        option.inSampleSize = calcuteInSapmleSize(option, reqWidth, reqHeight);
        //根据图片采样率加载图片
        option.inJustDecodeBounds = false;

        return BitmapFactory.decodeResource(resources, resID, option);
    }

    private static int calcuteInSapmleSize(BitmapFactory.Options option, int reqWidth, int reqHeight) {
        final int height = option.outHeight;
        final int width = option.outWidth;
        Log.e("info", "width======" + width+"\n"+"height======"+height);
        Log.e("info", "reqWidth======" + reqWidth+"\n"+"reqHeight======"+reqHeight);
        int inSample = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSample) >= reqHeight && (halfWidth / inSample) >= reqWidth) {
                inSample *= 2;
            }
        }
        Log.e("info", "inSample======" + inSample);
        return inSample;
    }


}

具体使用方法:
mImageView.setImageBitmap(BitmapUtil.decodeSampledbitmapFromResource(this.getResources(), R.mipmap.ic_launcher, 70, 70));


发布了75 篇原创文章 · 获赞 16 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览