1
0
mirror of https://github.com/DarthAffe/RGB.NET.git synced 2025-12-12 17:48:31 +00:00

Added more methods to work with HEX-colors

This commit is contained in:
Darth Affe 2018-06-10 17:21:35 +02:00
parent 96184d1220
commit 328074bfa2
2 changed files with 48 additions and 0 deletions

View File

@ -29,6 +29,32 @@
return new string(c);
}
// Source: https://web.archive.org/web/20180224104425/https://stackoverflow.com/questions/623104/byte-to-hex-string/3974535
/// <summary>
/// Converts the HEX-representation of a byte array to that array.
/// </summary>
/// <param name="hexString">The HEX-string to convert.</param>
/// <returns>The correspondending byte array.</returns>
public static byte[] HexToBytes(string hexString)
{
if ((hexString.Length == 0) || ((hexString.Length % 2) != 0))
return new byte[0];
byte[] buffer = new byte[hexString.Length / 2];
for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
{
// Convert first half of byte
char c = hexString[sx];
buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? ((c - 'a') + 10) : ((c - 'A') + 10)) : (c - '0')) << 4);
// Convert second half of byte
c = hexString[++sx];
buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? ((c - 'a') + 10) : ((c - 'A') + 10)) : (c - '0'));
}
return buffer;
}
#endregion
}
}

View File

@ -215,6 +215,28 @@ namespace RGB.NET.Core
return new Color(a, r, g, b);
}
/// <summary>
/// Creates a new instance of the <see cref="T:RGB.NET.Core.Color" /> struct using a HEX-string.
/// </summary>
/// <param name="hexString">The HEX-representation of the color.</param>
/// <returns>The color created from the HEX-string.</returns>
public static Color FromHexString(string hexString)
{
if ((hexString == null) || (hexString.Length < 6))
throw new ArgumentException("Invalid hex string", nameof(hexString));
if (hexString[0] == '#')
hexString = hexString.Substring(1);
byte[] data = ConversionHelper.HexToBytes(hexString);
if (data.Length == 3)
return new Color(data[0], data[1], data[2]);
if (data.Length == 4)
return new Color(data[0], data[1], data[2], data[3]);
throw new ArgumentException("Invalid hex string", nameof(hexString));
}
#endregion
private static (double h, double s, double v) CaclulateHSVFromRGB(byte r, byte g, byte b)