Tuesday, December 8, 2009

Color Distance

We can represent a color in Java ME using integer literals. The four bytes represent different aspects of the color:

  • Transparency: also known as Alpha channel. Indicates if the color should we drawn as solid or translucid

  • Red: the red component

  • Green: the green component

  • Blue: the blue component

In a previous post I pointed how to get the handset theme color dinamically with Display.getColor.
But I came to a situation where I could not use COLOR_HIGHLIGHTED_BACKGROUND with COLOR_HIGHLIGHTED_FOREGROUND.
The colors were too "close". Like dark gray over black.

My work around was to add a color distance verification. Lets imagine that the three color components are the axis of a 3D system.
To calculate the distance between two colors (two points) I just need to apply the below method:

public static int colorDistance (int c1, int c2) {
int r1 = (c1 & 0xff0000) >> 16;
int g1 = (c1 & 0x00ff00) >> 8;
int b1 = c1 & 0x0000ff;
int r2 = (c2 & 0xff0000) >> 16;
int g2 = (c2 & 0x00ff00) >> 8;
int b2 = c2 & 0x0000ff;

// http://en.wikipedia.org/wiki/Euclidean_metric
return sqrtRound(((r2 - r1) * (r2 - r1)) +
((g2 - g1) * (g2 - g1)) +
((b2 - b1) * (b2 - b1)));

I chose that if color distance if below or equal to 40 I should use black color for foreground and white color for background.

Related topics:

No comments: