2016-11-30 104 views
5

我有一個Xamarin.Forms.Color,我想將它轉換爲'十六進制值'。Xamarin.Forms.Color到十六進制值

到目前爲止,我還沒有找到解決我的問題。

我的代碼如下:

foreach (var cell in Grid.Children) 
{ 
    var pixel = new Pixel 
    { 
     XAttribute = cell.X , 

     YAttribute = cell.Y , 

     // I want to convert the color to a hex value here 

     Color = cell.BackgroundColor 

    }; 

} 

回答

22

只是權宜之計,最後一行是錯誤的。

Alpha通道而來的其他值前:

string hex = String.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", alpha, red, green, blue); 

,這是最好的一個擴展方法:

public static class ExtensionMethods 
{ 
    public static string GetHexString(this Xamarin.Forms.Color color) 
    { 
     var red = (int)(color.R * 255); 
     var green = (int)(color.G * 255); 
     var blue = (int)(color.B * 255); 
     var alpha = (int)(color.A * 255); 
     var hex = $"#{alpha:X2}{red:X2}{green:X2}{blue:X2}"; 

     return hex; 
    } 
} 
7
 var color = Xamarin.Forms.Color.Orange; 
     int red = (int) (color.R * 255); 
     int green = (int) (color.G * 255); 
     int blue = (int) (color.B * 255); 
     int alpha = (int)(color.A * 255); 
     string hex = String.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", red, green, blue, alpha); 
+0

代碼諾克斯的答案是正確的語法。 「Alpha」頻道應該先到來 - https://developer.xamarin.com/api/type/Xamarin.Forms.Color/ – ethane