今天突然发现,图片放在drawable 不同分辨率的目录下会有不同程度的放大或者缩小?这是为什么呢?

首先我们从decodeResource()方法入手

public static Bitmap decodeResource(Resources res, int id, Options opts){  
//....
  final TypedValue value = new TypedValue();
   is = res.openRawResource(id, value);
    bm = decodeResourceStream(res, value, is, null, opts);
//.....
}
openRawResource解析资源,获取相关信息,这里是获取desinity ,drawable文件夹下是为0,mdpi===160  hdpi====240  以此类推
DisplayMetrics.DENSITY_DEFAULT=160
  public static Bitmap decodeResourceStream(Resources res, TypedValue value,
            InputStream is, Rect pad, Options opts) {

        if (opts == null) {
            opts = new Options();
        }

        if (opts.inDensity == 0 && value != null) {
            final int density = value.density;
            if (density == TypedValue.DENSITY_DEFAULT) {
                opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
            } else if (density != TypedValue.DENSITY_NONE) {
                opts.inDensity = density;
            }
        }
        
        if (opts.inTargetDensity == 0 && res != null) {
            opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
        }
        
        return decodeStream(is, pad, opts);
    }

如果没有设置 inTargetDensity,就获得设备的densityDpi,最终根据inTargetDensity和包含该图片的文件夹的denisty作比较进行缩放。

 
posted on 2016-10-26 16:49  向着大牛奋斗  阅读(540)  评论(0编辑  收藏  举报