Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android change color of ImageView / Bitmap

I need to find a way to change the color of bitmap in Android. I need to replace/change colors of oval image smoothly in my application depending on int value. I need something like if myValue=5 than change my image's color to RED and if myValue=322 change color to BLUE. The only way which I find I can do this was using xml file which looks like this :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
 <solid android:color="#cccccc"/> 
    <corners
     android:bottomRightRadius="10dp"
     android:bottomLeftRadius="10dp"
     android:topLeftRadius="10dp"
     android:topRightRadius="10dp"/>
</shape>

and after that when myValue is changing to set my ImageView image resource. But in this way I have to create 35 different xml files...which I don't think is a good idea.

So anyone who can suggest better solution to do this?

like image 424
Android-Droid Avatar asked May 04 '12 13:05

Android-Droid


People also ask

How do I change the color of a bitmap image?

Click Bitmaps Bitmap color mask. Choose a color from the list of masked colors. Click the Edit color button . Use the controls in the Select color dialog box to edit the color.

How to change drawable Image color in android?

This example demonstrates how to change the colors of a Drawable in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

This is how I solved this issue :

  1. Declare an ImageView with src="@drawable/button"
  2. Create a Drawable and set ColorFilter to it and after that use it as src to your declared ImageView like this :

>

Drawable myIcon = getResources().getDrawable( R.drawable.button );
ColorFilter filter = new LightingColorFilter( Color.BLUE, Color.BLUE );
myIcon.setColorFilter(filter);
color.setImageDrawable(myIcon);
like image 184
Android-Droid Avatar answered Oct 13 '22 14:10

Android-Droid