Viewing is open to everyone. Downloading and starring need a GitHub sign-in.
Sign in with GitHub
CKeyColor.cs
v0.1.0-build.85
Latest
Commit ede38f5
Sign in with GitHub to download. Each download is recorded with your GitHub username.
| 1 | using System; |
| 2 | using System.Globalization; |
| 3 | using OpenCKey.Interop; |
| 4 | |
| 5 | namespace OpenCKey |
| 6 | { |
| 7 | /// <summary>An opaque sRGB colour (<c>ckey_rgb</c>).</summary> |
| 8 | public readonly struct CKeyColor : IEquatable<CKeyColor> |
| 9 | { |
| 10 | /// <summary>Creates a colour from its channels.</summary> |
| 11 | public CKeyColor(byte r, byte g, byte b) |
| 12 | { |
| 13 | R = r; |
| 14 | G = g; |
| 15 | B = b; |
| 16 | } |
| 17 | |
| 18 | /// <summary>Red channel.</summary> |
| 19 | public byte R { get; } |
| 20 | /// <summary>Green channel.</summary> |
| 21 | public byte G { get; } |
| 22 | /// <summary>Blue channel.</summary> |
| 23 | public byte B { get; } |
| 24 | |
| 25 | /// <summary>Black.</summary> |
| 26 | public static CKeyColor Black => new CKeyColor(0, 0, 0); |
| 27 | /// <summary>White.</summary> |
| 28 | public static CKeyColor White => new CKeyColor(255, 255, 255); |
| 29 | |
| 30 | /// <summary>From 0xRRGGBB.</summary> |
| 31 | public static CKeyColor FromRgb(int rgb) => new CKeyColor((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); |
| 32 | |
| 33 | /// <summary>Parses "#rrggbb" or "rrggbb".</summary> |
| 34 | public static CKeyColor Parse(string hex) |
| 35 | { |
| 36 | if (hex == null) throw new ArgumentNullException(nameof(hex)); |
| 37 | string s = hex.StartsWith("#", StringComparison.Ordinal) ? hex.Substring(1) : hex; |
| 38 | if (s.Length != 6 || !int.TryParse(s, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out int v)) |
| 39 | throw new FormatException($"'{hex}' is not a #rrggbb colour."); |
| 40 | return FromRgb(v); |
| 41 | } |
| 42 | |
| 43 | /// <summary>"#rrggbb".</summary> |
| 44 | public override string ToString() => $"#{R:x2}{G:x2}{B:x2}"; |
| 45 | |
| 46 | /// <inheritdoc /> |
| 47 | public bool Equals(CKeyColor other) => R == other.R && G == other.G && B == other.B; |
| 48 | /// <inheritdoc /> |
| 49 | public override bool Equals(object? obj) => obj is CKeyColor c && Equals(c); |
| 50 | /// <inheritdoc /> |
| 51 | public override int GetHashCode() => (R << 16) | (G << 8) | B; |
| 52 | /// <summary>Equality.</summary> |
| 53 | public static bool operator ==(CKeyColor a, CKeyColor b) => a.Equals(b); |
| 54 | /// <summary>Inequality.</summary> |
| 55 | public static bool operator !=(CKeyColor a, CKeyColor b) => !a.Equals(b); |
| 56 | |
| 57 | internal NativeRgb ToNative() => new NativeRgb { R = R, G = G, B = B }; |
| 58 | internal static CKeyColor FromNative(NativeRgb c) => new CKeyColor(c.R, c.G, c.B); |
| 59 | } |
| 60 | } |