|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using System.Drawing; |
| 7 | +using System.Text.RegularExpressions; |
| 8 | + |
| 9 | +namespace WebUntisAPI.Client.Extensions |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Extensions for the <see cref="Color"/> struct |
| 13 | + /// </summary> |
| 14 | + public static class ColorExtensions |
| 15 | + { |
| 16 | + /// <summary> |
| 17 | + /// Convert a color instance to the Hexadeciaml format: RRGGBB |
| 18 | + /// </summary> |
| 19 | + /// <param name="color"></param> |
| 20 | + /// <returns>The color string</returns> |
| 21 | + public static string ToHexColorFormat(this Color color) |
| 22 | + { |
| 23 | + return color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"); |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Convert a color string to the Hexadecimal format: RRGGBB |
| 28 | + /// </summary> |
| 29 | + /// <param name="color"></param> |
| 30 | + /// <returns>The created color</returns> |
| 31 | + /// <exception cref="ArgumentException">Thrown when the <paramref name="colorString"/> isn't in the correct format</exception> |
| 32 | + public static Color FromHexColorFormat(this Color color, string colorString) |
| 33 | + { |
| 34 | + if (!Regex.IsMatch(colorString, @"[\da-fA-F]{6}")) |
| 35 | + throw new ArgumentException("The color string isn't in a correct format", nameof(colorString)); |
| 36 | + |
| 37 | + // Convert the hex string to the single color channels |
| 38 | + int red = Convert.ToByte(colorString.Substring(0, 2), 16); |
| 39 | + int green = Convert.ToByte(colorString.Substring(2, 2), 16); |
| 40 | + int blue = Convert.ToByte(colorString.Substring(4, 2), 16); |
| 41 | + |
| 42 | + return Color.FromArgb(red, green, blue); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | +} |
0 commit comments