J2ME Customizing Game Sprites Color

Often in games a nice feature to give to users it the possibility to customize their own character, for example changing colors of the different parts (hairs, eyes, shirt, and so on).

Image:J2me_custom_colors.png

To support this features there are 2 possibilities:

  • Include a different image for each color of each different part
  • Replace colors by code

The second options will save you the effort to create these multiple images, and will strip down your JAR size. Also, it will allow you to support a lot more colors.

You can see a simple midlet showing the following snipped of code in action on this page.

Here is the code that takes your input image, the color to be replaced and the new color, and returns a new image.

Some notes on this code:

  • The Image.getRGB method() returns colors as effectively represented by phone, so they can be different from the original colors of your image. This is the reason why we use the getDeviceColor to get the effective color to be replaced, since on different phones it can be represented differently.
  • The limit of this approach is that if 2 different colors of your image map to the same color (because the phone has a limited range of available colors), both of them will be replaced with the new color.
  • A simple optimization of this code will be to store the rbg[] data in a variable, to reuse it for all the color replacement operations
import javax.microedition.lcdui.Image;
 
public class ColorChanger
{
public static Image changeColor(Image source, int fromColor, int toColor)
{
int imageWidth = source.getWidth();
int imageHeight = source.getHeight();

int[] rgb = new int[imageWidth * imageHeight];

int deviceColor = getDeviceColor(fromColor);

source.getRGB(rgb, 0, imageWidth, 0, 0, imageWidth, imageHeight);
 
for(int i = 0; i < rgb.length; i++)
{
if(rgb[i] == deviceColor)
{
rgb[i] = toColor;
}
}
return Image.createRGBImage(rgb, imageWidth, imageHeight, true);
}
static int getDeviceColor(int color)
{
Image fake = Image.createRGBImage(new int[]{color}, 1, 1, false);

int[] rgb = new int[1];

fake.getRGB(rgb, 0, 1, 0, 0, 1, 1);

return rgb[0];
}
}
 
01-07 1053
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值