2004. július 12., hétfő

Find the contrasting colour


Problem/Question/Abstract:

Is there some kind of function that - given a background color - would return the most appropriate text and highlighted text colors? For example, suppose I have a cell in a stringgrid with some text in > it. Some of the text will be highlighted with a different color. When a user changes the background color for the cell I need a function to change to the most appropriate highlight and text color.

Answer:

It's easy to find a contrasting color for the text; imagine the background color resides inside a three-dimensional color cube with axes labeled red, green, and blue. The corner of the cube farthest away from the background color will always be contrasting. Untested:

function FindContrastingColor(Color: TColor): TColor;
var
  R, G, B: Byte;
begin
  R := GetRValue(Color);
  G := GetGValue(Color);
  B := GetBValue(Color);
  if (R < 128) then
    R := 255
  else
    R := 0;
  if (G < 128) then
    G := 255
  else
    G := 0;
  if (B < 128) then
    B := 255
  else
    B := 0;
  Result := RGB(R, G, B);
end;

As for the highlight color, you might try a hue 180 degrees distant from the background. You'll need to transform the RGB value into HSV, adjust the H value, then transform back to RGB.

Nincsenek megjegyzések:

Megjegyzés küldése