Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

c# - Xamarin.Forms.Color to hex value

I have a Xamarin.Forms.Color and I want to convert it to a 'hex value'.

So far, I haven't found a solution to my problem.

My code is as follows:

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
    };
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just a quick fix, the last line is wrong.

Alpha channel comes before the other values:

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

and this is best for an extension method:

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...