需要为图像视图设置色调…我使用它的方式如下:

imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);

但这并没有改变……


当前回答

免责声明:这不是本文的答案。但它是这个问题的答案,即如何重置可绘制或imageview的颜色/色调。对不起,把这个放在这里,因为这个问题不接受答案,请参阅这篇文章的答案。所以,把它加在这里,这样人们在寻找解决方案时就会得到这个。

正如@RRGT19在这个回答的评论中提到的。我们可以使用setImageTintList()和传递null作为tintList来重置颜色。它神奇地为我工作。

ImageViewCompat.setImageTintList(imageView, null)

其他回答

从棒棒糖开始,还有一个用于BitmapDrawables的着色方法,它与新的Palette类一起工作:

(ColorStateList tint)

and

setTintMode (portterduff . setintmode)模式tintMode)

在旧版本的Android上,你现在可以使用DrawableCompat库

得益于ADev,更简化了扩展函数

fun ImageView.setTint(@ColorRes colorRes: Int) {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
}

用法:-

imageView.setTint(R.color.tintColor)
Random random=new Random;
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
ColorFilter cf = new PorterDuffColorFilter(Color.rgb(random.nextInt(255), random.nextInt(255), random.nextInt(255)),Mode.OVERLAY);

imageView.setImageResource(R.drawable.ic_bg_box);
imageView.setColorFilter(cf);

@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方法太多…)

在android中以编程方式设置图像视图的色调

我有两个方法为android:

1)

imgView.setColorFilter(context.getResources().getColor(R.color.blue));

2)

 DrawableCompat.setTint(imgView.getDrawable(),
                     ContextCompat.getColor(context, R.color.blue));

我希望我能帮到大家:-)