码迷,mamicode.com
首页 > 其他好文 > 详细

关于Bitmap的加载(一)

时间:2015-04-09 13:33:44      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

  Android中的Bitmap的加载,为了更好的用户体验,有非常多的奇巧淫技。要达到的目的是,一边加载一边看,不卡屏。图片根据布局大小显示。如果图片大了,要合理的缩小,防止内存溢出。

  于是,我把Android training的讲解记录下来。

  首先,是单一图片的加载。

  单一图片,加载最首要的问题是判断图片的大小。如果图片过大,我们需要对图片进行一定比例的压缩。

  先通过图片本身的宽高和要求的宽高,计算图片的缩放比例。

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

  其中,options中包含了图片本身的宽高信息,会在调用这个函数前获得。

  然后,是对图片加载时参数的设置  

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

  最后,我们即可以调用相应方法,加载图片。

mImageView.setImageBitmap(
    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

以上,即是将图片压缩到100X100的大小进行加载,图片来源即为R.id.myimage。但是,这样的图片加载,当图片太大时,会引进UI界面的卡顿,下一节将记录如果将这一过程分发至其他线程,保持UI界面的流畅。

关于Bitmap的加载(一)

标签:

原文地址:http://www.cnblogs.com/fishbone-lsy/p/4409251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!