From: David Roqueni <45717673+DavidRoqueni@users.noreply.github.com> Date: Thu, 4 Jul 2019 00:13:01 +0000 (-0700) Subject: Add Color.ToHex() (#6272) X-Git-Tag: accepted/tizen/5.5/unified/20200421.150457~317 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=1c9fe47d1ed6252a31102affe4860530b8ed1383;p=platform%2Fcore%2Fcsapi%2Fxsf.git Add Color.ToHex() (#6272) * Updated Color to have ToHex() method. Created Unit tests to ensure method is working as expected. * Updated ToHex() use uint values. Updated unit tests for ToHex. fixes #6003 --- diff --git a/Xamarin.Forms.Core.UnitTests/ColorUnitTests.cs b/Xamarin.Forms.Core.UnitTests/ColorUnitTests.cs index 8668e5b..e217f5a 100644 --- a/Xamarin.Forms.Core.UnitTests/ColorUnitTests.cs +++ b/Xamarin.Forms.Core.UnitTests/ColorUnitTests.cs @@ -225,6 +225,23 @@ namespace Xamarin.Forms.Core.UnitTests } [Test] + public void TestToHex() + { + var colorRgb = Color.FromRgb(138, 43, 226); + Assert.AreEqual(Color.FromHex(colorRgb.ToHex()), colorRgb); + var colorRgba = Color.FromRgba(138, 43, 226,.2); + Assert.AreEqual(Color.FromHex(colorRgba.ToHex()), colorRgba); + var colorHsl = Color.FromHsla(240, 1, 1); + Assert.AreEqual(Color.FromHex(colorHsl.ToHex()),colorHsl); + var colorHsla = Color.FromHsla(240, 1, 1,.1); + var hexFromHsla = Color.FromHex(colorHsla.ToHex()); + Assert.That(hexFromHsla.A, Is.EqualTo(colorHsla.A).Within(0.002)); + Assert.That(hexFromHsla.R, Is.EqualTo(colorHsla.R).Within(0.001)); + Assert.That(hexFromHsla.G, Is.EqualTo(colorHsla.G).Within(0.001)); + Assert.That(hexFromHsla.B, Is.EqualTo(colorHsla.B).Within(0.001)); + } + + [Test] public void FromRGBDouble () { var color = Color.FromRgb (0.2, 0.3, 0.4); diff --git a/Xamarin.Forms.Core/Color.cs b/Xamarin.Forms.Core/Color.cs index 305d833..c52ae6d 100644 --- a/Xamarin.Forms.Core/Color.cs +++ b/Xamarin.Forms.Core/Color.cs @@ -301,6 +301,15 @@ namespace Xamarin.Forms return string.Format(CultureInfo.InvariantCulture, "[Color: A={0}, R={1}, G={2}, B={3}, Hue={4}, Saturation={5}, Luminosity={6}]", A, R, G, B, Hue, Saturation, Luminosity); } + public string ToHex() + { + var red = (uint)(R * 255); + var green = (uint)(G * 255); + var blue = (uint)(B * 255); + var alpha = (uint)(A * 255); + return $"#{alpha:X2}{red:X2}{green:X2}{blue:X2}"; + } + static uint ToHex (char c) { ushort x = (ushort)c; @@ -311,7 +320,7 @@ namespace Xamarin.Forms if (x >= 'a' && x <= 'f') return (uint)(x - 'a' + 10); return 0; - } + } static uint ToHexD (char c) {