Advertisement
Guest User

Color hex parser

a guest
Feb 27th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | None | 0 0
  1. //using System.Globalization;
  2. public static Color ParseColor(string hex) {
  3.             int length = hex.Length;
  4.             if(length != 6 && length != 8)
  5.                 throw new ArgumentException($"Color Hex code {hex} is not a valid hex code.");
  6.  
  7.             var color = new Color32();
  8.             if(
  9.                 byte.TryParse(hex.Substring(0, 2), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out byte r) &&
  10.                 byte.TryParse(hex.Substring(2, 2), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out byte g) &&
  11.                 byte.TryParse(hex.Substring(4, 2), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out byte b))
  12.             {
  13.                 color.r = r;
  14.                 color.b = b;
  15.                 color.g = g;
  16.             } else
  17.                 throw new ArgumentException($"Color Hex code {hex} is not a valid hex code.");
  18.  
  19.             if(length == 8)
  20.                 if(byte.TryParse(hex.Substring(6, 2), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out byte a))
  21.                     color.a = a;
  22.                 else
  23.                     throw new ArgumentException($"Color Hex code {hex} is not a valid hex code.");
  24.             else
  25.                 color.a = 0xFF;
  26.  
  27.             return color;
  28.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement