This week I encountered a color contrast test problem at work: that is, the foreground color of the text on the webpage should be compared with the background color of the text
Wcag (Web Content Accessibility guide. This document provides some standard requirements for web content, so that your website content can be accessed to the best possible level. There is one ( G18 According to the formula, the color contrast must meet the requirements of at least 4.5: 1, which makes it easier for human eyes to distinguish the background color from the foreground color. Here is my personal C # implementation:
/// <Summary>
/// Convert hexadecimal color values to RGB Arrays
/// </Summary>
/// <Param name = "hexadecimal"> Color hexadecimal value eg: # ff1a2b </Param>
/// <Returns> RGB Array </Returns>
Public Byte [] Converthex ( String Hexadecimal)
{
Byte [] Resultbyte = New Byte [ 3 ];
Int Num = 0 ;
Hexadecimal = Hexadecimal. Trim ( ' # ' );
// It is possible to input an argb value.
If (Hexadecimal. Length > 6 )
{
Hexadecimal = Hexadecimal. Remove ( 0 , 2 );
}
For ( Int I = 0 ; I < 6 ; I ++ )
{
If (I % 2 = 0 )
{
Stringbuilder sb = New Stringbuilder ();
SB. append (hexadecimal [I]);
SB. append (hexadecimal [I + 1 ]);
Resultbyte [num ++ ] = Convert. tobyte (sb. tostring (), 16 );
}
}
Return Resultbyte;
}
/// <Summary>
/// Compare two-color contrast
/// </Summary>
/// <Param name = "rgb1"> </param>
/// <Param name = "rgb2"> </param>
/// <Returns> Comparison Value </Returns>
Public Double Colorcompare ( Byte [] Rgb1, Byte [] Rgb2)
{
Double L1 = Relativeluminance (rgb1 );
Double L2 = Relativeluminance (rgb2 );
Double Result = (Math. Max (L1, L2) + 0.05 ) / (Math. Min (L1, L2) + 0.05 );
Return Math. Round (result, 2 );
}
Private Double Relativeluminance ( Byte [] RGB)
{
Double RS = RGB [ 0 ] * 1.0 / 255 ;
Double GS = RGB [ 1 ] * 1.0 / 255 ;
Double BS = RGB [ 2 ] * 1.0 / 255 ;
Double R, G, B;
R = RS <= 0.03928 ? RS / 12.92 : Math. Pow (RS + 0.055 ) / 1.055 , 2.4 );
G = GS <= 0.03928 ? GS / 12.92 : Math. Pow (GS + 0.055 ) / 1.055 , 2.4 );
B = BS <= 0.03928 ? BS / 12.92 : Math. Pow (BS + 0.055 ) / 1.055 , 2.4 );
Return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}