android 动态改变图标颜色

本文主要介绍了如何在Android中动态改变应用图标的颜色。关键步骤包括获取图标像素点,检查并修改不透明像素的颜色,以实现根据指定颜色值更新图标颜色的功能。

关键点

  • 获取目标图标的所有像素点
  • 验证像素点的alpha值,是否透明
  • 在不透明的像素点上修改为我们想要的颜色

根据输入的颜色值改变图标颜色

final EditText et = findViewById(R.id.et);
final ImageView iv = findViewById(R.id.iv);
iv.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        //获取ImageView上的图片
        iv.setDrawingCacheEnabled(true);
        Bitmap bitmap = iv.getDrawingCache();

        //按照输入的颜色转换图标
        String s = et.getText().toString();
        Bitmap newBitmap = changeBitmapColor(bitmap,s);
        iv.setDrawingCacheEnabled(false);
        iv.setImageBitmap(newBitmap);
    }
});

实现方法:

public Bitmap changeBitmapColor(Bitmap sourceBitmap,String aimColorStr){
    //验证参数合理
    if(sourceBitmap == null || sourceBitmap.isRecycled()){
        throw new RuntimeException("source exception!!!");
    }
    int aimColor;
    try {
        aimColor = Color.parseColor(aimColorStr.trim());
    } catch (Exception e){
        throw new RuntimeException("aimColorStr error!!!");
    }
    //按照图标的大小创建数组
    int mBitmapWidth = sourceBitmap.getWidth();
    int mBitmapHeight = sourceBitmap.getHeight();
    int mArrayColorLengh = mBitmapWidth * mBitmapHeight;
    int[] mArrayColor = new int[mArrayColorLengh];

    //循环bitmap 的每个像素点,查看alpha值
    int count = 0;
    for (int i = 0; i < mBitmapHeight; i++) {
        for (int j = 0; j < mBitmapWidth; j++) {
            //获得Bitmap 图片中每一个点的color颜色值
            int color = sourceBitmap.getPixel(j, i);
            int a = Color.alpha(color);
            if(a != 0){//不等于0 即不透明部分,设置成我们想要的颜色
                mArrayColor[count] = aimColor;
            } else {//透明仍然为透明
                int aimColor2 = Color.parseColor("#00000000");
                mArrayColor[count] = aimColor2;
            }
            count++;
        }
    }
    //根据数组创建新的Bitmap
    Bitmap newBitmap = Bitmap.createBitmap(mBitmapWidth,mBitmapHeight, Bitmap.Config.ARGB_8888);
    newBitmap.setPixels(mArrayColor,0,mBitmapWidth,0,0,mBitmapWidth,mBitmapHeight);
    return newBitmap;
}
  • 效果
    这里写图片描述
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值