Ashni Goyal
Ashni Goyal

Reputation: 827

Dynamically changing the foreground color of an Image in Android Java (retaining the alpha transparency)

I have an image of red ball with transparent background. I want to change the color of ball to many other colors programatically without affecting the background i.e. background shall remain transparent. How this can be achieved in Android?

Upvotes: 1

Views: 1567

Answers (3)

Trần Sĩ Long
Trần Sĩ Long

Reputation: 477

Try:

//Bitmap bmp
//int color 
int[] pixels = new int[bmp.getWidth() * bmp.getHeight()];
bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0,
            bmp.getWidth(), bmp.getHeight());
for (int i = 0; i < pixels.length; i++) {
pixels[i] &= color;
}
Bitmap newBmp = Bitmap.createBitmap(bmp.getWidth(),
bmp.getHeight(), Config.ARGB_8888);
newBmp.setPixels(pixels, 0, newBmp.getWidth(), 0, 0, newBmp.getWidth(), newBmp.getHeight());

Upvotes: 1

Pattabi Raman
Pattabi Raman

Reputation: 5854

You can also achieve it by using Frame Animation. Use different pictures of same ball image with different ball colors, and use frame animation to run the images as frames.If so, the colors of ball looks to be changing.

Upvotes: -1

wattostudios
wattostudios

Reputation: 8764

You can use the Bitmap class to modify your image in this way, such as using the setPixel() method. You just need to make sure that the color still has its alpha set to transparent.

Refer to the Color documentation here for defining colors with their RGB and Alpha channels (you want to keep the alpha values of each pixel, and only change the RGB values). Also refer to the Bitmap documentation here

Upvotes: 2

Related Questions