需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
当前回答
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))
}
其他回答
得益于ADev,更简化了扩展函数
fun ImageView.setTint(@ColorRes colorRes: Int) {
ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
}
用法:-
imageView.setTint(R.color.tintColor)
@Hardik说得对。代码中的另一个错误是在引用xml定义的颜色时。你只将id传递给setColorFilter方法,而你应该使用id来定位颜色资源,并将资源传递给setColorFilter方法。重写下面的原始代码。
如果这一行在你的活动中:
imageView.setColorFilter(getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);
否则,你需要引用你的主活动:
Activity main = ...
imageView.setColorFilter(main.getResources().getColor(R.color.blue), android.graphics.PorterDuff.Mode.MULTIPLY);
注意,其他类型的资源也是如此,比如整数、bool、维度等。除了string,你可以直接在你的Activity中使用getString(),而不需要首先调用getResources()(不要问我为什么)。
否则,您的代码看起来很好。(虽然我还没有研究setColorFilter方法太多…)
正如@milosmns所说,你应该使用 imageView.setColorFilter (getResouces () .getColor (R.color.blue) android.graphics.PorterDuff.Mode.MULTIPLY);
这个API需要颜色值而不是颜色资源id,这就是为什么你的语句没有工作的根本原因。
如果你正在改变对焦的色调,请试试这个
DrawableCompat.setTint(imgView.getDrawable(),
ContextCompat.getColor(context, R.color.blue));
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))
}