Converting a string HEX to color in Windows Phone Runtime c#

前端 未结 8 1671
执念已碎
执念已碎 2021-02-09 07:30

I am working on a windows phone game, and I got stuck when I wanted to convert a HEX string into Color. On windows phone 8 silverlight it is not a problem but I cannot find a so

8条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-09 08:15

    Final solution, that works as well on UWP:

     public static Color GetColorFromHex(string hexString) {
                //add default transparency to ignore exception
                if ( !string.IsNullOrEmpty(hexString) && hexString.Length > 6 ) {
                    if ( hexString.Length == 7 ) {
                        hexString = "FF" + hexString;
                    }
    
                    hexString = hexString.Replace("#", string.Empty);
                    byte a = (byte) ( Convert.ToUInt32(hexString.Substring(0, 2), 16) );
                    byte r = (byte) ( Convert.ToUInt32(hexString.Substring(2, 2), 16) );
                    byte g = (byte) ( Convert.ToUInt32(hexString.Substring(4, 2), 16) );
                    byte b = (byte) ( Convert.ToUInt32(hexString.Substring(6, 2), 16) );
                    Color color = Color.FromArgb(a, r, g, b);
                    return color;
                }
    
                //return black if hex is null or invalid
                return Color.FromArgb(255, 0, 0, 0);
            }
    

提交回复
热议问题