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

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

但这并没有改变……


当前回答

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

其他回答

试试这个。它应该适用于支持库支持的所有Android版本:

public static Drawable getTintedDrawableOfColorResId(@NonNull Context context, @NonNull Bitmap inputBitmap, @ColorRes int colorResId) {
    return getTintedDrawable(context, new BitmapDrawable(context.getResources(), inputBitmap), ContextCompat.getColor(context, colorResId));
}

public static Drawable getTintedDrawable(@NonNull Context context, @NonNull Bitmap inputBitmap, @ColorInt int color) {
    return getTintedDrawable(context, new BitmapDrawable(context.getResources(), inputBitmap), color);
}

public static Drawable getTintedDrawable(@NonNull Context context, @NonNull Drawable inputDrawable, @ColorInt int color) {
    Drawable wrapDrawable = DrawableCompat.wrap(inputDrawable);
    DrawableCompat.setTint(wrapDrawable, color);
    DrawableCompat.setTintMode(wrapDrawable, PorterDuff.Mode.SRC_IN);
    return wrapDrawable;
}

你可以使用上面的任何一个来使它工作。

你可以在这里阅读DrawableCompat文档中更多有趣的特性。

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

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

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

用法:-

imageView.setTint(R.color.tintColor)

大多数答案指的是使用setColorFilter,这不是最初的问题。

用户@Tad的答案是正确的,但它只适用于API 21+。

要设置所有Android版本的色调,使用ImageViewCompat:

ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(yourTint));

注意,在这种情况下,yourTint必须是一个“颜色int”。如果你有一个像r。color这样的颜色资源。蓝色,你需要先加载颜色int:

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