Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two System.Drawing.Color structures represent the same color in 16 bit color depth?

How can I check if two System.Drawing.Color structures represent the same color in 16 bit color depth (or generally based on the value of Screen.PrimaryScreen.BitsPerPixel)?

Let's say I set Form.TransparencyKey to Value1 (of Color type), I want to check that when the user selects a new background color for the form (Value2), I don't set the entire form transparent.

On 32bit color depth screens I simply compare the two values:

if (Value1 == Value2)

However, this does not work on 16bit color depth screens, as more Color values for the Value2 would represent the same actual 16bit color as Value1, as I found out the hard way.

like image 819
Alex Vang Avatar asked Feb 02 '10 14:02

Alex Vang


2 Answers

Try the following code:

void MyTestMethod() {
    TransparencyKey = Color.FromArgb(128, 128, 64);
    BackColor = Color.FromArgb(128, 128, 71);

    byte tR = ConvertR(TransparencyKey.R);
    byte tG = ConvertG(TransparencyKey.G);
    byte tB = ConvertB(TransparencyKey.B);

    byte bR = ConvertR(BackColor.R);
    byte bG = ConvertG(BackColor.G);
    byte bB = ConvertB(BackColor.B);

    if (tR == bR &&
        tG == bG &&
        tB == bB) {
        MessageBox.Show("Equal: " + tR + "," + tG + "," + tB + "\r\n" +
            bR + "," + bG + "," + bB);
    }
    else {
        MessageBox.Show("NOT Equal: " + tR + "," + tG + "," + tB + "\r\n" +
            bR + "," + bG + "," + bB);
    }
}

byte ConvertR(byte colorByte) {
    return (byte)(((double)colorByte / 256.0) * 32.0);
}

byte ConvertG(byte colorByte) {
    return (byte)(((double)colorByte / 256.0) * 64.0);
}

byte ConvertB(byte colorByte) {
    return (byte)(((double)colorByte / 256.0) * 32.0);
}

Just fiddle with the TransparancyKey and BackColor to see if it works for you. For me it did. And yes, I know it's bloated and ugly code, it's just meant as example of course.

like image 135
Webleeuw Avatar answered Oct 06 '22 00:10

Webleeuw


There are two pixel formats for 16-bit color, 555 and 565. You'd have to mask the R, G and B values with 0xf8 (5 bits) and 0xfc (6 bits) before comparing them. Do keep in mind that the machine on which you run the designer is not representative for the machine on which your program runs.

like image 41
Hans Passant Avatar answered Oct 05 '22 22:10

Hans Passant