aplavin
aplavin

Reputation: 2229

Applying ColorFilter to ImageView with ShapedDrawable

I have an ImageView with android:src set to a ShapedDrawable, namely a white circle. What I want is to colorize this ImageView in runtime responding to some events. imgView.setColorFilter seems to be solution, but after using this (tried different parameters) the image becomes invisible (I don't see it at the screen).

How to solve this? And are there better ways to have color circles?

Upvotes: 42

Views: 89213

Answers (4)

Vansuita Jr.
Vansuita Jr.

Reputation: 2099

You can do it very very simple using this library: https://github.com/jrvansuita/IconHandler

It will working like this:

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

Upvotes: 0

Volodymyr Yatsykiv
Volodymyr Yatsykiv

Reputation: 3211

You can use attribute android:tint in ImageView in xml.

Example:

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

Tested on Android 4.1.2 and 6.0.1

Upvotes: 8

Vishwas Vaishnav
Vishwas Vaishnav

Reputation: 317

If you want to change Image Color use

PorterDuff.Mode.SRC_ATOP instead
PorterDuff.Mode.MULTIPLY

in above example.

Upvotes: 17

MH.
MH.

Reputation: 45493

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:

Screenshot of colored circles

Upvotes: 109

Related Questions