以前做了一个流量悬浮窗,悬浮窗里有当前网络状态的图标和网速的文字,想实现改变文字颜色的同时改变状态图标的颜色
实现后分享出来让大家参考下
先上图
以下是关键代码
<ImageView
android:id="@+id/iv_icon"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@drawable/icon"/>
//设置图标的颜色
private void setIconColor(ImageView icon, int r, int g, int b, int a) {
float[] colorMatrix = new float[]{
0, 0, 0, 0, r,
0, 0, 0, 0, g,
0, 0, 0, 0, b,
0, 0, 0, (float) a / 255, 0
};
icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
}
想知道具体原理的可以看一下这篇文章
Android学习笔记22:图像颜色处理(ColorMatrix)
如果图标是不透明的并且不需要透明度的变化,还有更简单的实现方法
icon.setColorFilter(Color.argb(255, r, g, b));