mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-06-19 13:28:16 +08:00

committed by
Patrik Svensson

parent
9aa36c4cf0
commit
bcfc495843
@ -57,16 +57,22 @@ namespace Spectre.Console.Internal
|
||||
var color = ColorTable.GetColor(part);
|
||||
if (color == null)
|
||||
{
|
||||
if (!foreground)
|
||||
if (part.StartsWith("#", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
error = $"Could not find color '{part}'.";
|
||||
color = ParseHexColor(part, out error);
|
||||
if (!string.IsNullOrWhiteSpace(error))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
error = $"Could not find color or style '{part}'.";
|
||||
}
|
||||
error = !foreground
|
||||
? $"Could not find color '{part}'."
|
||||
: $"Could not find color or style '{part}'.";
|
||||
|
||||
return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (foreground)
|
||||
@ -95,5 +101,42 @@ namespace Spectre.Console.Internal
|
||||
error = null;
|
||||
return new Style(effectiveForeground, effectiveBackground, effectiveDecoration);
|
||||
}
|
||||
|
||||
private static Color? ParseHexColor(string hex, out string error)
|
||||
{
|
||||
error = null;
|
||||
|
||||
hex = hex ?? string.Empty;
|
||||
hex = hex.Replace("#", string.Empty).Trim();
|
||||
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(hex))
|
||||
{
|
||||
if (hex.Length == 6)
|
||||
{
|
||||
return new Color(
|
||||
(byte)Convert.ToUInt32(hex.Substring(0, 2), 16),
|
||||
(byte)Convert.ToUInt32(hex.Substring(2, 2), 16),
|
||||
(byte)Convert.ToUInt32(hex.Substring(4, 2), 16));
|
||||
}
|
||||
else if (hex.Length == 3)
|
||||
{
|
||||
return new Color(
|
||||
(byte)Convert.ToUInt32(new string(hex[0], 2), 16),
|
||||
(byte)Convert.ToUInt32(new string(hex[1], 2), 16),
|
||||
(byte)Convert.ToUInt32(new string(hex[2], 2), 16));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = $"Invalid hex color '#{hex}'. {ex.Message}";
|
||||
return null;
|
||||
}
|
||||
|
||||
error = $"Invalid hex color '#{hex}'.";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user