应用ColorFilter到的ImageView与ShapedDrawable应用ColorFilt

2019-05-13 11:49发布

我有一个ImageViewandroid:src设置为ShapedDrawable ,即白圈。 我想要的是上色本ImageView在运行时响应一些事件。 imgView.setColorFilter似乎是解决方案,但采用这种后(尝试不同的参数)的图像变得不可见(我没有看到它在屏幕)。

如何解决这个问题? 以及是否有更好的方法来有色界?

Answer 1:

Alright, I had a quick play with this and noticed your issue of the circles disappearing. Without you describing what exactly you tried, I assume you haven't tried setting the color filter to the Drawable itself yet? (as opposed to the ImageView, which only seems to work with BitmapDrawables).

The following statements work perfectly fine for an xml-declared ShapeDrawable with white as initial color:

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

The ShapeDrawable for completeness: (I set the size on the ImageView, see below)

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

And one of the ImageViews as example:

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

Visual result:



Answer 2:

如果你想改变图像色彩使用

PorterDuff.Mode.SRC_ATOP instead
PorterDuff.Mode.MULTIPLY

在上面的示例。



Answer 3:

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

例:

<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



Answer 4:

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

它会这样工作:

Icon.on(yourImageView).color(R.color.your_color).icon(R.mipmap.your_icon).put();


文章来源: Applying ColorFilter to ImageView with ShapedDrawable