1
0

Added HtmlHelper.IsDarkColor and enhanced UnitTests

This commit is contained in:
2021-12-17 00:14:38 +01:00
parent 6f6b79c88c
commit cea79c2359
4 changed files with 468 additions and 5 deletions

View File

@@ -0,0 +1,55 @@
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace AMWD.Common.AspNetCore.Utilities
{
/// <summary>
/// Provides helpers for webpages.
/// </summary>
public static class HtmlHelper
{
/// <summary>
/// Checks whether a color is considered as dark.
/// </summary>
/// <param name="color">The color (hex or rgb - as defined in CSS)</param>
/// <returns><c>true</c> when the color is dark otherwise <c>false</c>.</returns>
public static bool IsDarkColor(string color)
{
if (string.IsNullOrWhiteSpace(color))
return false;
int r, g, b;
var rgbMatch = Regex.Match(color, @"^rgba?\(([0-9]+), ?([0-9]+), ?([0-9]+)");
var hexMatchFull = Regex.Match(color, @"^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$");
var hexMatchLite = Regex.Match(color, @"^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$");
if (rgbMatch.Success)
{
r = Convert.ToInt32(rgbMatch.Groups[1].Value);
g = Convert.ToInt32(rgbMatch.Groups[2].Value);
b = Convert.ToInt32(rgbMatch.Groups[3].Value);
}
else if (hexMatchFull.Success)
{
r = Convert.ToInt32(hexMatchFull.Groups[1].Value, 16);
g = Convert.ToInt32(hexMatchFull.Groups[2].Value, 16);
b = Convert.ToInt32(hexMatchFull.Groups[3].Value, 16);
}
else if (hexMatchLite.Success)
{
r = Convert.ToInt32(new string(hexMatchLite.Groups[1].Value.First(), 2), 16);
g = Convert.ToInt32(new string(hexMatchLite.Groups[2].Value.First(), 2), 16);
b = Convert.ToInt32(new string(hexMatchLite.Groups[3].Value.First(), 2), 16);
}
else
{
return false;
}
double luminance = (r * 0.299 + g * 0.587 + b * 0.114) / 255;
return luminance <= 0.5;
}
}
}