zoukankan      html  css  js  c++  java
  • 关于Bitmap的加载(一)

      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界面的流畅。

  • 相关阅读:
    蓝桥杯_买不到的数目
    蓝桥杯_错误票据
    蓝桥杯_数组操作
    剑指OFFER_把二叉树打印成多行
    C语言学习笔记_结构体的内存对齐
    剑指OFFER_二叉搜索树的第k个节点
    局域网ftp工具,带你去探索局域网ftp工具
    这就是Java代码生成器的制作流程(转载)
    ftp工具 绿色,一款非常棒的绿色 ftp工具
    HDFS+ClickHouse+Spark:从0到1实现一款轻量级大数据分析系统(转载)
  • 原文地址:https://www.cnblogs.com/fishbone-lsy/p/4409251.html
Copyright © 2011-2022 走看看