Applying ColorFilter to ImageView with ShapedDrawable

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

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

+29
android drawable android-imageview colorfilter shapedrawable
Apr 11 2018-12-12T00:
source share
4 answers

Well, I quickly played with it and noticed that your problem is the disappearance of circles. If you did not indicate what exactly you tried, I assume that you have not yet tried to set the color filter to Drawable ? (unlike ImageView , which only works with BitmapDrawable s).

The following statements work fine for declared xml ShapeDrawable with white as the 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 ); 

ShapeDrawable for completeness: (I set the size on 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 from ImageView as an 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:

Screenshots of colored circles

+92
Apr 13 2018-12-12T00:
source share

If you want to change the color of the image, use

 PorterDuff.Mode.SRC_ATOP instead PorterDuff.Mode.MULTIPLY 

in the above example.

+11
Dec 14 '15 at 11:53 on
source share

You can use android:tint attribute 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

+5
Nov 25 '16 at 15:14
source share

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

It will work as follows:

 Icon.on(yourImageView).color(R.color.your_color).icon(R.mipmap.your_icon).put(); 
0
Mar 14 '17 at 11:56 on
source share



All Articles