Friday, September 25, 2009

Dynamically change color of Node icon(2)

I blogged about the way to change the color of an icon dynamically here. Now, I have encountered that when I add those icons to a list of nodes or menu items, all icons get the color of the last one changed. Hmpf.

It looks like that ImageUtilities.loadImage(..) somehow caches the icon and hence even when assuming working on a new copy we still work on the common one.

The way I got it working was to forcefully create a new BufferedImage and merge in the one just loaded. The new code looks like this



private BufferedImage icon16;
private BufferedImage icon32;
public static final String PROP_ID = "id";
public static final String PROP_NAME = "displayName";
public static final String PROP_COMMENT = "comment";
public static final String PROP_COLOR = "color";
public static final String PROP_ICON16 = "icon16";
public static final String PROP_ICON32 = "icon32";

// ...

public Image getSmallImage() {
int width = icon16.getWidth();
int height = icon16.getHeight();

BufferedImage newImage = new BufferedImage(width,height,BufferedImage.TYPE_4BYTE_ABGR);
newImage = (BufferedImage)ImageUtilities.mergeImages(icon16, newImage, 0, 0);

for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgb = newImage.getRGB(x, y);
if (newImage.getRGB(x, y) < 0) {
rgb = some_method_returning_the_RGB_for_a_selected_color;
newImage.setRGB(x, y, rgb);
}
}
}
return newImage;
}

// ...

private void loadIcons() {
String iconId = props.getProperty(PROP_ICON16);
icon16 = (BufferedImage)ImageUtilities.loadImage(iconId);
iconId = props.getProperty(PROP_ICON32);
icon32 = (BufferedImage)ImageUtilities.loadImage(iconId);
}




And it now respects each individual color.

No comments:

Post a Comment