Android 代码改变图标颜色及动态生成Drawerable Selector

本文介绍了一种在Android开发中动态改变图标颜色的方法,并提供了具体的实现代码。通过使用该方法可以为图标创建不同状态(如按下和选中状态)的Selector文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创文章,如有转载,请注明出处:http://blog.youkuaiyun.com/myth13141314/article/details/64906237

Android 开发中Drawerable的Selector文件用得很频繁,有时候图标文件只有默认的,缺少选中状态或是按下状态的图标资源,这个时候就需要用代码改变图标的颜色,动态生成Selector文件


改变图标的颜色

主要就是改变画笔的颜色重新绘制

/*
* change image color
* @params context
* @params resId, the image resource need to change color
* @params color, target color, default is white
* 
* @return bitmap
*
* */
public static Bitmap changeImageColor(Context context, int resId, int color) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);

        Bitmap mAlphaBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mAlphaBitmap);
        Paint mPaint = new Paint();
        if (color != 0) {
            mPaint.setColor(color);
        }else {
            mPaint.setColor(Color.parseColor("#FFFFFF"));
        }
        Bitmap alphaBitmap = bitmap.extractAlpha();
        mCanvas.drawBitmap(alphaBitmap, 0, 0, mPaint);

        return mAlphaBitmap;
    }
将Bitmap转化为Drawerable
new BitmapDrawable(context.getResources(), bitmap)

生成Selector文件
/*
* 生成selector
* 
* */
public static StateListDrawable initSelector(Context context, int normal) {
    StateListDrawable states = new StateListDrawable();

    //按下状态
    states.addState(new int[] {android.R.attr.state_pressed},
            new BitmapDrawable(context.getResources(), changeImageColor(context, normal, Color.parseColor("#eb3636"))));

    //选中状态
    states.addState(new int[] {android.R.attr.state_selected},
            new BitmapDrawable(context.getResources(), changeImageColor(context, normal, Color.parseColor("#eb3636"))));

    if (Build.VERSION.SDK_INT > LOLLIPOP) {
        states.addState(new int[] {}, context.getResources().getDrawable(normal, null));
    }else {
        states.addState(new int[] {}, context.getResources().getDrawable(normal));
    }

    return states;
}
应用
imageView.setImageDrawable(initSelector(context, R.mipmap.icon))

虽然还是让设计切图来得方便,但是掌握一些基本的技巧还是很有必要的


欢迎关注我的公众号,和我一起每天进步一点点!
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值