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

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

但这并没有改变……


当前回答

因为第一个答案对我不起作用:

//get ImageView
ImageView myImageView = (ImageView) findViewById(R.id.iv);

//colorid is the id of a color defined in values/colors.xml
myImageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(), R.color.colorid)));

这似乎只适用于API 21+,但对我来说这不是问题。不过,您可以使用ImageViewCompat来解决这个问题。

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

其他回答

试试这个。它应该适用于支持库支持的所有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文档中更多有趣的特性。

这对我很有效

mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));

在我使用的java中

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

正如@milosmns所说,你应该使用 imageView.setColorFilter (getResouces () .getColor (R.color.blue) android.graphics.PorterDuff.Mode.MULTIPLY);

这个API需要颜色值而不是颜色资源id,这就是为什么你的语句没有工作的根本原因。

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

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

widgetIcon是ImageView selectedColor是来自colorPicker的颜色

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