需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
当前回答
kotlin中的一个扩展函数,用于设置和取消设置着色。
fun ImageView.setTint(@ColorRes color: Int?) {
if (color == null) {
ImageViewCompat.setImageTintList(this, null)
} else {
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, color)))
}}
用法:yourImageView.setTint(R.color.white)用于设置和删除:
其他回答
正如@milosmns所说,你应该使用 imageView.setColorFilter (getResouces () .getColor (R.color.blue) android.graphics.PorterDuff.Mode.MULTIPLY);
这个API需要颜色值而不是颜色资源id,这就是为什么你的语句没有工作的根本原因。
Kotlin解决方案使用扩展功能,设置和取消设置着色:
fun ImageView.setTint(@ColorInt color: Int?) {
if (color == null) {
ImageViewCompat.setImageTintList(this, null)
return
}
ImageViewCompat.setImageTintMode(this, PorterDuff.Mode.SRC_ATOP)
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(color))
}
如果你想将选择器设置为你的色调:
ImageViewCompat.setImageTintList(iv, getResources().getColorStateList(R.color.app_icon_click_color));
这对我很有效
mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));
如果你的颜色有十六进制透明度,使用下面的代码。
ImageViewCompat.setImageTintMode(imageView, PorterDuff.Mode.SRC_ATOP);
ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(Color.parseColor("#80000000")));
清除色彩
ImageViewCompat.setImageTintList(imageView, null);