56 lines
1.7 KiB
C#
56 lines
1.7 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|