需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
当前回答
在我使用的java中
imageView.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)));
其他回答
试试这个。它应该适用于支持库支持的所有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));
如果你正在改变对焦的色调,请试试这个
DrawableCompat.setTint(imgView.getDrawable(),
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))
}
更新: @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);