2015-03-25 58 views
2

我想從我的Windows 8移動應用程序中的Web顏色值設置邊框背景顏色。如何獲取System.Windows.Media.Color來自HEX Windows 8應用程序

我發現一個方法,轉換十六進制ARGB但它不是爲我工作..

private System.Windows.Media.Color FromHex(string hex) 
     { 
      string colorcode = hex; 
      int argb = Int32.Parse(colorcode.Replace("#", ""), System.Globalization.NumberStyles.HexNumber); 
      return System.Windows.Media.Color.FromArgb((byte)((argb & -16777216) >> 0x18), 
            (byte)((argb & 0xff0000) >> 0x10), 
            (byte)((argb & 0xff00) >> 8), 
            (byte)(argb & 0xff)); 


     } 

我使用上述方法如..

 Border borderCell = new Border(); 
    var col = FromHex("#DD4AA3"); 
    var color =new System.Windows.Media.SolidColorBrush(col); 
    borderCell.Background = color; 

但是如果我通過顏色的十六進制值如下

  var col = FromHex("#FFEEDDCC"); 

它的工作正常,但它不工作我的十六進制顏色值。

在發佈這個問題之前,我會通過這個堆棧的答案。 How to get Color from Hexadecimal color code using .NET?

Convert System.Drawing.Color to RGB and Hex Value

+0

我不明白你的這一行'它的工作正常,但它不適用於我的十六進制顏色值。「這是什麼意思」它不適用於我的十六進制顏色值。「?第二件事是你在第二個例子'#FFEEDDCC'中提供了alpha值。確保您的方法在提供了alpha值(前兩個字符)時轉換十六進制值 – Shell 2015-03-25 08:44:53

+0

System.Windows.Media.ColorConverter類通常有助於進行轉換。但它在手機上不可用,因此您基本上需要複製[此代碼](http://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Media/Parsers.cs,53f793cda4dc02b2)。 – 2015-03-25 09:47:49

回答

5

終於讓我找到一個方法,從十六進制字符串

public System.Windows.Media.Color ConvertStringToColor(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 System.Windows.Media.Color.FromArgb(a, r, g, b); 
    } 
+1

你的努力完全值得! – 2015-10-06 11:04:15

-1

爲什麼不能簡單地用System.Windows.Media.ColorConverter返回顏色?

Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString(「#EA1515」);

+0

因爲這個關於'Windows-phone'的問題與'WPF'無關。 – 2016-03-25 05:58:30

相關問題