Xamarin.Forms.Color to hex value

后端 未结 4 652
广开言路
广开言路 2020-12-15 19:49

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:



        
相关标签:
4条回答
  • 2020-12-15 20:34

    a bit late but here is how I do that in Xamarin Forms (the Xamarin.Forms.Color class already exposes a FromHex(string) method.

    public string ColorHexa { get; set; }
    public Color Color
    {
        get => Color.FromHex(ColorHexa);
        set => ColorHexa = value.ToHexString();
    }
    

    With this extension :

    public static class ColorExtensions
    {
        public static string ToHexString(this Color color, bool outputAlpha = true)
        {
            string DoubleToHex(double value)
            {
                return string.Format("{0:X2}", (int)(value * 255));
            }
    
            string hex = "#";
            if (outputAlpha) hex += DoubleToHex(color.A);
            return $"{hex}{DoubleToHex(color.R)}{DoubleToHex(color.G)}{DoubleToHex(color.B)}";
        }
    }
    
    0 讨论(0)
  • 2020-12-15 20:34

    This will give you the hex color in the format #{Alpha}{R}{G}{B}.

    For example #FFFF0000 for Red.

    color.ToHex();
    
    0 讨论(0)
  • 2020-12-15 20:49
    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 讨论(0)
  • 2020-12-15 20:50

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题