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

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

但这并没有改变……


当前回答

在我使用的java中

imageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)));

其他回答

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

在图像上方放置另一个视图 您可以随意更改视图的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,更简化了扩展函数

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

用法:-

imageView.setTint(R.color.tintColor)

加上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项目中都有用的功能!

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

我得到的解决方案,特别是在情况下,如果你改变颜色通过任何colorPicker库返回一个整数值的selectedColor。

widgetIcon是ImageView selectedColor是来自colorPicker的颜色

var imageDrawable: Drawable = widgetIcon.background
        imageDrawable = DrawableCompat.wrap(imageDrawable)
        DrawableCompat.setTint(imageDrawable, selectedColor)
        widgetIcon.background = imageDrawable

我发现我们可以为tint attr使用颜色选择器:

mImageView.setEnabled(true);

activity_main.xml:

<ImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_arrowup"
    android:tint="@color/section_arrowup_color" />

section_arrowup_color.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/white" android:state_enabled="true"/>
    <item android:color="@android:color/black" android:state_enabled="false"/>
    <item android:color="@android:color/white"/>
</selector>