Join Now
Quality Rating:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)
Expertise Level:
  • Currently 4.0 / 5
(4.0 / 5 - 1 vote cast)

This page was last modified 10:00, 14 April 2008.

J2ME Customizing Game Sprites Color

From Forum Nokia Wiki


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];
	}
}
Related Discussions
Thread Thread Starter Forum Replies Last Post
Graphical Software for J2ME game thongtom Mobile Java Media (Graphics & Sounds) 4 2005-11-07 13:36
how pc - pc communication through j2se and bluetooth Arifa Bluetooth Technology 6 2007-09-08 09:38
Adding Images davewit13 Mobile Java Media (Graphics & Sounds) 8 2005-02-11 07:31
Game crashes on Nokia 3650 lla2 Mobile Java Games 14 2008-03-09 16:41
bluetooth pushing Jar files steve_richards Bluetooth Technology 6 2007-06-23 13:50
 
Powered by MediaWiki