How to check if two System.Drawing.Color structures represent the same color with a color depth of 16 bits?

How to check if two System.Drawing.Color structures correspond to the same color with a color depth of 16 bits (or even based on the value of Screen.PrimaryScreen.BitsPerPixel)?

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

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

if (Value1 == Value2)

However, this does not work on 16-bit color depth screens, since more color values ​​for Value2 will represent the same actual 16-bit color as Value1, as I found the hard way.

+7
c # colors winforms 16-bit system.drawing.color
source share
3 answers

Try using 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 play with TransparancyKey and BackColor to see if this works for you. It was like that for me. And yes, I know this is bloated and ugly code, it's just an example, of course.

+1
source share

There are two pixel formats for 16-bit color, 555 and 565. Before matching them, you will have to mask the values ​​of R, G and B with 0xf8 (5 bits) and 0xfc (6 bits). Keep in mind that the machine on which you run the constructor is not representative of the machine on which your program is running.

+1
source share

Since ColorTranslator.ToWin32 is used under the hood, does it work?

 if( ColorTranslator.ToWin32(Value1) == ColorTranslator.ToWin32(Value2) ) 
0
source share

All Articles