android drawable.setAlpha设置无效的解决办法

公司项目有一个需求,图标从网络下载,根据不同的状态设置不同的透明度,于是想当然地这么写:

Drawable drawable = imageView.getDrawable();
drawable.setAlpha(alpha);       

结果有些图标设置成功了,有些失败。调试发现,成功的都是SquaringDrawable,而失败的都是BitmapDrawable。

进一步调试发现,SquaringDrawable是Glide框架的,BitmapDrawable是系统的。查找资料得知,BitmapDrawable调用setAlpha不是直接调用其自身的Paint,而是通过一个mBitmapState来实现,这个mBitmapState是底层共享的,至于怎么修改,不得而知。不过我们可以通过调用Drawable的mutate()方法来阻断这种共享性,这是BitmapDrawable的mutate()方法源码:

    @Override
    public Drawable mutate() {
        if (!mMutated && super.mutate() == this) {
            mBitmapState = new BitmapState(mBitmapState);
            mMutated = true;
        }
        return this;
    }

解决方案:

结合Glide代码,我是这么写的:

Glide.with(mContext)
                .load(url)
                .asBitmap()
                .error(R.drawable.ic_app_load)
                .placeholder(R.drawable.ic_app_load)
                .dontAnimate()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);
                        drawable.mutate();
                        imageView.setImageDrawable(drawable);
                    }
                });

这里,我在源头上指定了imageView的drawable为BitmapDrawable,并调用mutate()方法,而不是由glide自动为我们指定drawable类型。注意,当imageView设置drawable后,再调用mutate()方法阻断已经晚了。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值