Bitmap ImageView大小探究

本文探究了ImageView在设置Bitmap时的大小计算原理,涉及到Bitmap的density、targetDensity以及ImageView的实际大小。通过实验展示了如何通过修改options影响Bitmap的解码大小,并揭示了ImageView的大小由BitmapDrawable的intrinsicWidth和intrinsicHeight决定,而这两个值受targetDensity影响。最后强调了选择正确density资源文件夹对内存使用的重要性。
摘要由CSDN通过智能技术生成

前言

我们平时在使用ImageView,当设置宽高为wrap_content的时候,设置bitmap,有没有想过一个问题,那就是大小究竟是如何计算的,平时说的那些density又和最终显示的图片大小有什么关系呢。本着严谨的态度,我开始了探索源码解读的不归路上。

过程

本次实验所用测试机density为420。我们首先来解码一张bitmap(ic_launcher大小为144 * 144),代码如下:

      val options = BitmapFactory.Options()
      val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher, options)
      Log.d("Bitmap", "{height: ${bitmap.height}  ---  width: ${bitmap.width}}")

打印结果是{height: 126 — width: 126},那么这个数值是怎么来的呢。我们进入decodeResource一看究竟,

    public static Bitmap decodeResource(Resources res, int id, Options opts) {
        validate(opts);
        Bitmap bm = null;
        InputStream is = null; 
        
        try {
            final TypedValue value = new TypedValue();
            is = res.openRawResource(id, value);

            bm = decodeResourceStream(res, value, is, null, opts);
        } catch (Exception e) {
            /*  do nothing.
                If the exception happened on open, bm will be null.
                If it happened on close, bm is still valid.
            */
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (bm == null && opts != null && opts.inBitmap != null) {
            throw new IllegalArgumentException("Problem decoding into existing bitmap");
        }

        return bm;
    }

bitmap是decodeResourceStream产生的,那我们接着往下看,

    @Nullable
    public static Bitmap decodeResourceStream(@Nullable Resources res, @Nullable TypedValue value,
            @Nullable InputStream is, @Nullable Rect pad, @Nullable Options opts) {
        validate(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);
    }

可以看到,如果options.inDensity等于0,这里会对options做赋值操作,inDensity指的是图片资源所在资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值