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

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

但这并没有改变……


当前回答

在我尝试了所有的方法后,他们都不适合我。

我通过使用另一个PortDuff.MODE来获得解决方案。

imgEstadoBillete.setColorFilter(context.getResources().getColor(R.color.green),PorterDuff.Mode.SRC_IN);

其他回答

更新: @ADev在他的回答中有更新的解决方案,但他的解决方案需要更新的支持库- 25.4.0或以上。


你可以改变色调,很容易在代码中通过:

imageView.setColorFilter(颜色。Argb (255, 255, 255, 255));//白色色调

如果你想要色彩鲜艳的话

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);

对于可绘制的向量

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);

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

(ColorStateList tint)

and

setTintMode (portterduff . setintmode)模式tintMode)

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

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);

不是确切的答案,而是一个更简单的选择:

在图像上方放置另一个视图 您可以随意更改视图的alpha值(以编程方式)以获得所需的效果。

以下是其中的一个片段:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:contentDescription="@string/my_description"
        android:scaleType="fitXY"
        android:src="@drawable/my_awesome_image"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/height120"
        android:alpha="0.5"
        android:background="@color/my_blue_color"/>
</FrameLayout>

加上ADev的答案(在我看来是最正确的),因为Kotlin的广泛采用,以及它有用的扩展函数:

fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
    val color = ContextCompat.getColor(context, colorId)
    val colorStateList = ColorStateList.valueOf(color)
    ImageViewCompat.setImageTintList(this, colorStateList)
}

我认为这是一个在任何Android项目中都有用的功能!