2013-05-24 2 views
0

У меня есть код Шестнадцатеричный код «FFB800», и мне нужно было преобразовать его в «Цвет» в WinRT.Как преобразовать шестнадцатеричный код в цвет в окнах 8

Спасибо заранее.

+0

To * what * цвет? –

+0

Из того, что я нашел до сих пор, кажется, что вы можете создавать «цвет» в WinRT из отдельных компонентов RGB. Таким образом, вы можете разобрать это на int, а затем отделить байты, а затем создать «цвет» (который, возможно, внутренне объединит их с одним int снова). – harold

+0

Интересно, почему кто-то мог бы опросить этот вопрос ... особенно без комментариев и потери репутации. –

ответ

5

Какова цель этого вопроса? Возможно ли это сделать в простом XAML? XAML выполняет шестнадцатеричные коды.

<Grid Background="#FFB800"> 

В противном случае в код-за я использовал более или менее следующие в Windows 8 App:

var hexCode = "#FFFFB800"; 
    var color = new Color(); 
    color.A = byte.Parse(hexCode.Substring(1, 2), NumberStyles.AllowHexSpecifier); 
    color.R = byte.Parse(hexCode.Substring(3, 2), NumberStyles.AllowHexSpecifier); 
    color.G = byte.Parse(hexCode.Substring(5, 2), NumberStyles.AllowHexSpecifier); 
    color.B = byte.Parse(hexCode.Substring(7, 2), NumberStyles.AllowHexSpecifier); 
+0

Да, я хотел использовать в коде позади –

3

Короткий способ сделать это в твиттере:

(Color)XamlReader.Load(string.Format("<Color xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation …\">{0}</Color>", c)); 

Рекомендуемый способ, чтобы получить WinRT XAML Toolkit от NuGet и вызвать

WinRTXamlToolkit.Imaging.ColorExtensions.FromString(c); 

Это работает намного быстрее, чем при использовании XamlReader, поэтому рекомендуется, если вам нужно позвонить его более одного раза. Вы можете также клонировать его из GitHub или скопировать и вставить здесь:

#region FromString() 
/// <summary> 
/// Returns a Color based on XAML color string. 
/// </summary> 
/// <param name="c">The color string. Any format used in XAML should work.</param> 
/// <returns></returns> 
public static Color FromString(string c) 
{ 
    if (string.IsNullOrEmpty(c)) 
     throw new ArgumentException("Invalid color string.", "c"); 

    if (c[0] == '#') 
    { 
     switch (c.Length) 
     { 
      case 9: 
      { 
       //var cuint = uint.Parse(c.Substring(1), NumberStyles.HexNumber); 
       var cuint = Convert.ToUInt32(c.Substring(1), 16); 
       var a = (byte)(cuint >> 24); 
       var r = (byte)((cuint >> 16) & 0xff); 
       var g = (byte)((cuint >> 8) & 0xff); 
       var b = (byte)(cuint & 0xff); 

       return Color.FromArgb(a, r, g, b); 
      } 
      case 7: 
      { 
       var cuint = Convert.ToUInt32(c.Substring(1), 16); 
       var r = (byte)((cuint >> 16) & 0xff); 
       var g = (byte)((cuint >> 8) & 0xff); 
       var b = (byte)(cuint & 0xff); 

       return Color.FromArgb(255, r, g, b); 
      } 
      case 5: 
      { 
       var cuint = Convert.ToUInt16(c.Substring(1), 16); 
       var a = (byte)(cuint >> 12); 
       var r = (byte)((cuint >> 8) & 0xf); 
       var g = (byte)((cuint >> 4) & 0xf); 
       var b = (byte)(cuint & 0xf); 
       a = (byte)(a << 4 | a); 
       r = (byte)(r << 4 | r); 
       g = (byte)(g << 4 | g); 
       b = (byte)(b << 4 | b); 

       return Color.FromArgb(a, r, g, b); 
      } 
      case 4: 
      { 
       var cuint = Convert.ToUInt16(c.Substring(1), 16); 
       var r = (byte)((cuint >> 8) & 0xf); 
       var g = (byte)((cuint >> 4) & 0xf); 
       var b = (byte)(cuint & 0xf); 
       r = (byte)(r << 4 | r); 
       g = (byte)(g << 4 | g); 
       b = (byte)(b << 4 | b); 

       return Color.FromArgb(255, r, g, b); 
      } 
      default: 
       throw new FormatException(string.Format("The {0} string passed in the c argument is not a recognized Color format.", c)); 
     } 
    } 
    else if (
     c.Length > 3 && 
     c[0] == 's' && 
     c[1] == 'c' && 
     c[2] == '#') 
    { 
     var values = c.Split(','); 

     if (values.Length == 4) 
     { 
      var scA = double.Parse(values[0].Substring(3)); 
      var scR = double.Parse(values[1]); 
      var scG = double.Parse(values[2]); 
      var scB = double.Parse(values[3]); 

      return Color.FromArgb(
       (byte)(scA * 255), 
       (byte)(scR * 255), 
       (byte)(scG * 255), 
       (byte)(scB * 255)); 
     } 
     else if (values.Length == 3) 
     { 
      var scR = double.Parse(values[0].Substring(3)); 
      var scG = double.Parse(values[1]); 
      var scB = double.Parse(values[2]); 

      return Color.FromArgb(
       255, 
       (byte)(scR * 255), 
       (byte)(scG * 255), 
       (byte)(scB * 255)); 
     } 
     else 
     { 
      throw new FormatException(string.Format("The {0} string passed in the c argument is not a recognized Color format (sc#[scA,]scR,scG,scB).", c)); 
     } 
    } 
    else 
    { 
     var prop = typeof(Colors).GetTypeInfo().GetDeclaredProperty(c); 
     return (Color)prop.GetValue(null); 
    } 
} 
#endregion 
+1

Вам не нужны эти '& 0xff''s btw, приведение к' byte' уже позаботится об этом – harold

1
 var hexCode = "#FFFFB800"; 
     var color = new Color(); 
     color.A = byte.Parse(hexCode.Substring(7, 2), NumberStyles.AllowHexSpecifier); 
     color.R = byte.Parse(hexCode.Substring(1, 2), NumberStyles.AllowHexSpecifier); 
     color.G = byte.Parse(hexCode.Substring(3, 2), NumberStyles.AllowHexSpecifier); 
     color.B = byte.Parse(hexCode.Substring(5, 2), NumberStyles.AllowHexSpecifier); 

, как установить, как заполнить для XAML прямоугольника объекта

rect.Fill = новый SolidColorBrush (цвет);

другое решение, как это работает, но возвращает параметры из строя , если у вас есть только 6 цифр, шестигранник, а не полный 8 просто установить а до 255

0

Попробуйте это:

public struct MyColor : Windows.UI.Color 
{ 
    /// <summary> 
    /// Convert hexdecimal value into color. 
    /// </summary> 
    /// <param name="hexCode">hexdecimal of color.</param> 
    /// <returns></returns> 
    public Windows.UI.Xaml.Media.Brush ColorToBrush(string hexCode) 
    { 
     hexCode = hexCode.Replace("#", ""); 

     if (hexCode.Length == 6) 
      return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.ColorHelper.FromArgb(255, 
       byte.Parse(hexCode.Substring(0, 2), System.Globalization.NumberStyles.HexNumber), 
       byte.Parse(hexCode.Substring(2, 2), System.Globalization.NumberStyles.HexNumber), 
       byte.Parse(hexCode.Substring(4, 2), System.Globalization.NumberStyles.HexNumber))); 
     else if (hexCode.Length == 8) 
     { 
      var color = new Windows.UI.Color(); 
      color.A = byte.Parse(hexCode.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier); 
      color.R = byte.Parse(hexCode.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier); 
      color.G = byte.Parse(hexCode.Substring(4, 2), System.Globalization.NumberStyles.AllowHexSpecifier); 
      color.B = byte.Parse(hexCode.Substring(6, 2), System.Globalization.NumberStyles.AllowHexSpecifier); 
     } 

     return null; 
    } 
} 
Смежные вопросы