color inversion

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi
Is there a method, or has anybody already ready written one to determine a
contrasting color to a background color for text. In my case during a paint
of a cell in a data grid.
Thanks
 
this gives the opposite of a color
TextBox1.ForeColor = Color.FromArgb(255 - TextBox1.BackColor.R, 255 -
TextBox1.BackColor.G, 255 - TextBox1.BackColor.B)

hth Peter
 
Peter said:
this gives the opposite of a color
TextBox1.ForeColor = Color.FromArgb(255 - TextBox1.BackColor.R, 255 -
TextBox1.BackColor.G, 255 - TextBox1.BackColor.B)

hth Peter

But that doesn't always give a contrasting colour as the OP wants. If
the color is close to 50% grey, the resulting colour with your method
will also be close to 50% grey.

Just off the top of my head, you could look at the greyvalue of the
color (20% red, 60% green, 20% blue) and then see if it's below 50%
grey, use white (or a very bright color) and if it's above 50% grey, use
black (or a dark color).

i.e.

dim nGrey,

nGrey = 0.2 * TextBox1.BackColor.R + 0.6 * TextBox1.BackColor.G + 0.2 *
TextBox1.BackColor.B

if nGrey>128 then
Texbox1.ForeColor(color.black)
Else
Texbox1.ForeColor(color.white)
Endif

btw those percentages come from the graphics world to convert color intp
greyscale, I didn't make them up.
 
you're right, it inverts the color it doesn't give the biggest contrast, I
think that in bobpowell's faq there's an example of what the op wants but
I'm not 100% sure

Peter
 
I don't believe there is any reliable method for what you want.
Heres a selection of methods (in VB) each of which has their own problems.

Private Function InvertColor(ByVal ColorIn As Color) As Color
Return Color.FromArgb(ColorIn.ToArgb Xor &HFFFFFF)
End Function

Private Function ContrastingColor(ByVal ColorIn As Color) As Color
If MidRange(ColorIn) Then Return Color.White
Return InvertColor(ColorIn)
End Function

Private Function MidRange(ByVal ColorIn As Color) As Boolean
Return ColorIn.R > 100 AndAlso ColorIn.R < 160 AndAlso _
ColorIn.G > 100 AndAlso ColorIn.G < 160 AndAlso _
ColorIn.B > 100 AndAlso ColorIn.B < 160
End Function

Private Function BlackOrWhite(ByVal colorin As Color) As Color
If colorin.GetBrightness < 0.5 Then
Return Color.White
End If
Return Color.Black
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top