Question

I derived the Canvas class where in the paint method I draw an Image. When clicking a Command I want to draw in the Canvas a rectangle and a String inside the rectangle , and the Image will still be displayed behind the rectangle, so I want to darken a bit the Image because I want to make a visual effect like the one when showing LWUIT Dialog ( the tint color of the hidden Form ). So how to darken a bit the canvas in this situation ?

Was it helpful?

Solution

Assuming that width and height of image are known, I'd probably first use use Image.getRGB to get ARGB values for image pixels.

Then, I'd scale the RGB values to make an effect of it becoming darker.

int[] darken(int[] argb, int percentage) {
    int[] result = new int[argb.length];
    for (int i = 0; i <argb.length; i++) {
        result[i] = darkenArgb(argb[i], percentage);
    }
    return result;
}

private int darkenArgb(int argb, int percentage) {
    return darkenByte(argb, 3, 100) // keep alpha as-is
            | darkenByte(argb, 2, percentage)
            | darkenByte(argb, 1, percentage)
            | darkenByte(argb, 0, percentage);
}

private int darkenByte(int argb, int index, int percentage) {
    if (percentage < 0 || percentage > 100) {
        throw new IllegalArgumentException("unexpected percentage: ["
               + percentage + "]");
    }
    if (index < 0 || index > 3) {
        throw new IllegalArgumentException("unexpected index: [" + index + "]");
    }
    int result = (argb >> index) & 0xFF;
    result = result * percentage / 100;
    return result << index;
}

From an array obtained with darken method, darkened image could be made using Image.createRGBImage

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top