I have a imageview that I want to change the color based on a user choice
From examples on the internet I see the only way to really do this is by going through and modifying each pixel... however it seems to be EXTREMELY slow
if I add this into my code, it takes long enough that it prompts the user to force close or wait
for(int i =0 ; i < mBitmap.getHeight(); ++i)
{
for(int g = 0; g < mBitmap.getWidth(); ++g)
开发者_开发知识库{
}
}
What is the best way to change the color of the image?
The Image is a small image 320x100 and is mostly transparent with a small image in the inside, the small image I want to change the color of
The Problem lies in using getPixel(x,y)
. Grabbing each pixel one by one is a very slow process. Instead use getPixels
void getPixels(int[] pixels, int offset, int stride, int x, int y, int width, int height)
Returns in pixels[] a copy of the data in the bitmap.
It'll return you an array of integers with the pixel values (and operate on that array and then use setPixels
) and it will be faster (although requires more memory)
For a small image this method will do. Stride is equal to the image width.
mBitmap.getPixels( pixels, 0 , mBitmap.getWidth(), 0, 0 , mBitmap.getWidth(), mBitmap.getHeight());
In order of complexity:
Check the samples in API demos for usage of ColorFilter and ColorMatrix. But since you described it as a image within an image that you are trying to modify, this may not apply.
Put your processing code on its own thread to avoid the Application Not Responding issue. Look into AsyncTask. You may need to have a wait animation running while its processing.
Consider OpenGL ES 1.x. Use the image as a texture and overlay a color with alpha to get the effect. Although this would have better performance, the complexity of adding UI elements would need to be taken into account (i.e. build your own).
精彩评论