需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
需要为图像视图设置色调…我使用它的方式如下:
imageView.setColorFilter(R.color.blue,android.graphics.PorterDuff.Mode.MULTIPLY);
但这并没有改变……
当前回答
如果你的颜色有十六进制透明度,使用下面的代码。
ImageViewCompat.setImageTintMode(imageView, PorterDuff.Mode.SRC_ATOP);
ImageViewCompat.setImageTintList(imageView, ColorStateList.valueOf(Color.parseColor("#80000000")));
清除色彩
ImageViewCompat.setImageTintList(imageView, null);
其他回答
这对我很有效
mImageView.setColorFilter(ContextCompat.getColor(getContext(), R.color.green_500));
在我尝试了所有的方法后,他们都不适合我。
我得到的解决方案,特别是在情况下,如果你改变颜色通过任何colorPicker库返回一个整数值的selectedColor。
widgetIcon是ImageView selectedColor是来自colorPicker的颜色
var imageDrawable: Drawable = widgetIcon.background
imageDrawable = DrawableCompat.wrap(imageDrawable)
DrawableCompat.setTint(imageDrawable, selectedColor)
widgetIcon.background = imageDrawable
加上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项目中都有用的功能!
正如@milosmns所说,你应该使用 imageView.setColorFilter (getResouces () .getColor (R.color.blue) android.graphics.PorterDuff.Mode.MULTIPLY);
这个API需要颜色值而不是颜色资源id,这就是为什么你的语句没有工作的根本原因。
我在派对上迟到了,但我没有看到我的解决方案。我们能够通过setImageResource()设置色调颜色,太(我的minSdkVersion是24)。
因此,首先,您需要创建一个选择器,并将其保存在/drawable资产文件夹(我称之为ic_color_white_green_search.xml)
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false">
<bitmap android:src="@drawable/ic_search"
android:tint="@color/branding_green"/>
</item>
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true">
<bitmap android:src="@drawable/ic_search"
android:tint="@color/branding_green"/>
</item>
<!-- Default -->
<item android:drawable="@drawable/ic_search"/>
然后像这样在代码中设置它:
val icon = itemView.findViewById(R.id.icon) as ImageButton
icon.setImageResource(R.drawable.ic_color_white_green_search)