关键点
- 获取目标图标的所有像素点
- 验证像素点的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;
}
- 效果
本文主要介绍了如何在Android中动态改变应用图标的颜色。关键步骤包括获取图标像素点,检查并修改不透明像素的颜色,以实现根据指定颜色值更新图标颜色的功能。
689

被折叠的 条评论
为什么被折叠?



