// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using att; using System.Globalization; using System.Runtime.Serialization; namespace math { /// /// A class containing extension methods for processing colors. /// public static class ColorExtensions { /// /// Indicates if the given string can be converted to an RGBA value using . /// /// The string to convert. /// True if the string can be converted, false otherwise. public static bool CanConvertStringToRgba( [CanBeNull] string stringColor ) { return stringColor?.StartsWith( "#" ) ?? false; } /// /// Converts the given string to an RGBA value. /// /// The string to convert. /// The converted RGBA value. public static uint StringToRgba( [CanBeNull] string stringColor ) { var intValue = 0xFF000000; if( stringColor != null ) { if( stringColor.StartsWith( "#" ) ) { if( stringColor.Length == "#000".Length && uint.TryParse( stringColor.Substring( 1, 3 ), NumberStyles.HexNumber, null, out intValue ) ) { intValue = ( ( intValue & 0x00F ) << 16 ) | ( ( intValue & 0x00F ) << 20 ) | ( ( intValue & 0x0F0 ) << 4 ) | ( ( intValue & 0x0F0 ) << 8 ) | ( ( intValue & 0xF00 ) >> 4 ) | ( ( intValue & 0xF00 ) >> 8 ) | ( 0xFF000000 ); } if( stringColor.Length == "#000000".Length && uint.TryParse( stringColor.Substring( 1, 6 ), NumberStyles.HexNumber, null, out intValue ) ) { intValue = ( ( intValue & 0x000000FF ) << 16 ) | ( intValue & 0x0000FF00 ) | ( ( intValue & 0x00FF0000 ) >> 16 ) | ( 0xFF000000 ); } if( stringColor.Length == "#00000000".Length && uint.TryParse( stringColor.Substring( 1, 8 ), NumberStyles.HexNumber, null, out intValue ) ) { intValue = ( ( intValue & 0x000000FF ) << 16 ) | ( intValue & 0x0000FF00 ) | ( ( intValue & 0x00FF0000 ) >> 16 ) | ( intValue & 0xFF000000 ); } } } return intValue; } /// /// Converts the given RGB value to a string. /// /// The RGB value to convert. /// The converted string. [NotNull] public static string RgbToString( int value ) { var r = ( value & 0x000000FF ); var g = ( value & 0x0000FF00 ) >> 8; var b = ( value & 0x00FF0000 ) >> 16; return $"#{r:X2}{g:X2}{b:X2}"; } /// /// Converts the given RGBA value to a string. /// /// The RGBA value to convert. /// The converted string. [NotNull] public static string RgbaToString( int value ) { var r = ( value & 0x000000FF ); var g = ( value & 0x0000FF00 ) >> 8; var b = ( value & 0x00FF0000 ) >> 16; var a = ( value & 0xFF000000 ) >> 24; return $"#{a:X2}{r:X2}{g:X2}{b:X2}"; } } }