42

我有一个ImageViewwithandroid:src设置为 a ShapedDrawable,即一个白色圆圈。我想要的是ImageView在运行时对它进行着色以响应某些事件。imgView.setColorFilter似乎是解决方案,但是在使用这个(尝试了不同的参数)之后,图像变得不可见(我在屏幕上看不到它)。

如何解决这个问题?有没有更好的方法来制作色环?

4

4 回答 4

108

好吧,我快速玩了一下,发现你的圈子消失了。没有您描述您到底尝试了什么,我假设您还没有尝试将滤色器设置为Drawable本身?(与 s 相反ImageView,它似乎只适用于BitmapDrawables)。

ShapeDrawable以下语句对于以白色为初始颜色的 xml 声明非常有效:

ImageView redCircle = (ImageView) findViewById(R.id.circle_red_imageview);
ImageView greenCircle = (ImageView) findViewById(R.id.circle_green_imageview);
ImageView blueCircle = (ImageView) findViewById(R.id.circle_blue_imageview);

// we can create the color values in different ways:
redCircle.getDrawable().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY );
greenCircle.getDrawable().setColorFilter(0xff00ff00, PorterDuff.Mode.MULTIPLY );
blueCircle.getDrawable().setColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY );

为了ShapeDrawable完整性:(我在 上设置了大小ImageView,见下文)

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <solid android:color="@android:color/white" />
</shape>

并以其中一个ImageView为例:

<ImageView
    android:id="@+id/circle_red_imageview"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:padding="5dp"
    android:src="@drawable/circle_white" />

视觉结果:

彩色圆圈截图

于 2012-04-13T13:20:03.177 回答
16

如果要更改图像颜色,请使用

PorterDuff.Mode.SRC_ATOP instead
PorterDuff.Mode.MULTIPLY

在上面的例子中。

于 2015-12-14T11:53:29.617 回答
8

您可以在 xml 中使用 ImageView 中的属性android:tint

例子:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/your_drawable"
    android:tint="@color/your_color" />

在 Android 4.1.2 和 6.0.1 上测试

于 2016-11-25T15:14:11.153 回答
0

你可以使用这个库非常简单地做到这一点: https ://github.com/jrvansuita/IconHandler

它将像这样工作:

Icon.on(yourImageView).color(R.color.your_color).icon(R.mipmap.your_icon).put();
于 2017-03-14T11:56:40.107 回答