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

前端 未结 8 1674
执念已碎
执念已碎 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:00

    Here is an easy to use code snippet

    public Color HexColor(String hex)
    {
     //remove the # at the front
     hex = hex.Replace("#", "");
    
     byte a = 255;
     byte r = 255;
     byte g = 255;
     byte b = 255;
    
     int start = 0;
    
     //handle ARGB strings (8 characters long)
     if (hex.Length == 8)
     {
         a = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
         start = 2;
     }
    
     //convert RGB characters to bytes
     r = byte.Parse(hex.Substring(start, 2), System.Globalization.NumberStyles.HexNumber);
     g = byte.Parse(hex.Substring(start+2, 2), System.Globalization.NumberStyles.HexNumber);
     b = byte.Parse(hex.Substring(start+4, 2), System.Globalization.NumberStyles.HexNumber);
    
     return Color.FromArgb(a, r, g, b);
    }
    

    and you can simply call like the below one

    Color c = HexColor("#99ccff");
    

    I tested this in winphone 8.1 and it works

    Reference

提交回复
热议问题