Converting a string HEX to color in Windows Phone

2020-06-04 03:00发布

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 solution in runtime because it doesn't include Color.FromArgb, or Color.FromName functions.

Does somebody have a function that converts string HEX to Color?

Thanks.

8条回答
我想做一个坏孩纸
2楼-- · 2020-06-04 03:22

Color.FromArgb is in the Windows.UI namespace. There isn't a Color.FromName method, but you can use the Colors.< name > properties or you can use reflection to look up the name from a string.

using System.Reflection;     // For GetRuntimeProperty
using System.Globalization;  // For NumberStyles
using Windows.UI;            // for Color and Colors
using Windows.UI.Xaml.Media; // for SystemColorBrush

// from #AARRGGBB string
byte a = byte.Parse(hexColor.Substring(1, 2),NumberStyles.HexNumber);
byte r = byte.Parse(hexColor.Substring(3, 2),NumberStyles.HexNumber);
byte g = byte.Parse(hexColor.Substring(5, 2),NumberStyles.HexNumber);
byte b = byte.Parse(hexColor.Substring(7, 2),NumberStyles.HexNumber);

Windows.UI.Color color = Color.FromArgb(a, r, g, b);
Windows.UI.Xaml.Media.SolidColorBrush br = new SolidColorBrush(color);

// From Name
var prop = typeof(Windows.UI.Colors).GetRuntimeProperty("Aqua");
if (prop != null)
{
    Color c = (Color) prop.GetValue(null);
    br = new SolidColorBrush(c);
}

// From Property
br = new SolidColorBrush(Colors.Aqua);
查看更多
Bombasti
3楼-- · 2020-06-04 03:25

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

查看更多
登录 后发表回答