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

前端 未结 8 1670
执念已碎
执念已碎 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);
            }
    
    0 讨论(0)
  • 2021-02-09 08:19

    generete a file namely: ColorUtils.cs

    using Windows.UI.Xaml.Markup;
    ....
     static class ColorUtils
        {
            public static Color GetColorFromHex(string hexString)
            {
                Color x =(Color)XamlBindingHelper.ConvertValue(typeof(Color), hexString);
                return x;
            }
        }
    

    and use it something like

    var acolor=(new SolidColorBrush(ColorUtils.GetColorFromHex("#F24C27")):
    

    or with alpha

    var acolor=(new SolidColorBrush(ColorUtils.GetColorFromHex("#4CF24C27")):
    
    0 讨论(0)
提交回复
热议问题