سؤال

Suppose I know the backcolor and I want to change the forecolor accordingly to make the text distinct from the background. For example, if the current text color (forecolor) is RED, for some change of user, the backcolor also becomes RED or close to RED (which will make the text illegible), in such a case, I want to change the forecolor using some colors blending formula to make it distinct from the backcolor and maintain the legibility.

Hope you can help, thanks.

هل كانت مفيدة؟

المحلول

Based on the information on this blog entry, I could come up with the following C# code, that returns either Color.Black or Color.White for the best contrast with the given (background) color:

public Color GetContrastingColor(Color backColor)
{
    int r = (int)backColor.R;
    int g = (int)backColor.G;
    int b = (int)backColor.B;

    int yiqSpace = ((r * 299) + (g * 587) + (b * 114)) / 1000;

    if (yiqSpace > 131)
    {
        return Color.Black;
    }
    else
    {
        return Color.White;
    }
}

The method uses YIQ to determine if a color is considered light or dark, and returns a constrasting color in return.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top