简体   繁体   中英

Android: change the color of a bitmap

比方说,我有这个位图,它是一个随机涂成全黑的形状,并说我想成为包来改变它的颜色,我的位图是否必须先全部涂成白色,还是有其他东西?

If you're using Canvas the way to alter the bitmap's color is to alter the bitmap itself. The steps involved are as follows:

Say you want to load an existing Bitmap you have somewhere and you want to tint it red somehow.

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap);

After that you want to modify the bitmap's pixels before you paint it onto the Canvas. You create an int array that will holds all your pixels.

int[] pixels;
bitmap.getPixels(pixels, 0, 0, 0, 0, width, height);

After that you need to modify the array (say, adding to the red component). However, right now all we have is int values inside a pixel array. R,G and B are all packed inside. How to retrieve them?

int red = Color.red(pixels[n]);
int green = Color.green(pixels[n]);
int blue= Color.blue(pixels[n]);

Then you modify the pixel's value by whatever you want, you could put it in a loop or however you like, and then put it back to the pixels array. Also, RGB values go from 0-255 because they are 8-bit values.

Right after that you would put them back using exactly the opposite function.

bitmap.setPixels(pixels, 0, 0, 0, 0, width, height);

And then you're ready to go calling Canvas.drawBitmap();

Keep in mind that this process ought to be slow if you do it frequently, besides Canvas is a slow way of doing thing's if you're interested in real-time apps such as games.

Hope it helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM