2012-07-31 83 views
2

在我的Windows Phone application中,我從xml獲取顏色,然後將其綁定到某個元素。
我發現在我的情況下我得到了錯誤的顏色。在Windows Phone中轉換顏色

這裏是我的代碼:

var resources = feedsModule.getResources().getColorResource("HeaderColor") ?? 
    FeedHandler.GetInstance().MainApp.getResources().getColorResource("HeaderColor"); 
    if (resources != null) 
    { 
     var colourText = Color.FromArgb(255,Convert.ToByte(resources.getValue().Substring(1, 2), 16), 
         Convert.ToByte(resources.getValue().Substring(3, 2), 16), 
         Convert.ToByte(resources.getValue().Substring(5, 2), 16)); 

所以轉換後的顏色,我得到錯誤的結果。在XML我有這樣的一個:

<Color name="HeaderColor">#FFc50000</Color> 

並將其轉換成#FFFFC500

+0

我認爲你應該要麼使用,而不是Color.FromArgb Color.FromRgb,或者你應該使用Color.FromArgb阿爾法爲0,而不是255 – 2012-07-31 10:03:30

+0

的Windows Phone沒有Color.FromRgb,只有顏色。 FromArgb。如果我使用阿爾法到0而不是255我得到白色 – revolutionkpi 2012-07-31 10:06:24

+0

因爲如果你使用0而不是255,顏色實際上是透明的,所以你應該離開255.你在這種情況下獲得紅色而不是藍色嗎? – 2012-07-31 10:08:48

回答

12

你應該使用一些第三方轉換器。

Here is one of them

然後你可以使用它,以便:

Color color = (Color)(new HexColor(resources.GetValue()); 

您也可以使用的方法從this link,它的工作原理也是如此。

public 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 Color.FromArgb(a, r, g, b); 
}