diff --git a/PowerKit.Tests/Extensions/ColorExtensionsTests.cs b/PowerKit.Tests/Extensions/ColorExtensionsTests.cs new file mode 100644 index 0000000..90b43c3 --- /dev/null +++ b/PowerKit.Tests/Extensions/ColorExtensionsTests.cs @@ -0,0 +1,40 @@ +using System.Drawing; +using FluentAssertions; +using PowerKit.Extensions; +using Xunit; + +namespace PowerKit.Tests.Extensions; + +public class ColorExtensionsTests +{ + [Fact] + public void ToHexString_Test() + { + // Act & assert + Color.FromArgb(255, 0x12, 0x34, 0x56).ToHexString().Should().Be("#123456"); + Color.FromArgb(128, 0xff, 0x00, 0x00).ToHexString().Should().Be("#FF0000"); + Color.FromArgb(255, 0x00, 0x00, 0x00).ToHexString().Should().Be("#000000"); + Color.FromArgb(255, 0xff, 0xff, 0xff).ToHexString().Should().Be("#FFFFFF"); + } + + [Fact] + public void ToRgb_Test() + { + // Act & assert + Color.FromArgb(255, 0x12, 0x34, 0x56).ToRgb().Should().Be(0x123456); + Color.FromArgb(0, 0x12, 0x34, 0x56).ToRgb().Should().Be(0x123456); + Color.FromArgb(255, 0x00, 0x00, 0x00).ToRgb().Should().Be(0x000000); + Color.FromArgb(255, 0xff, 0xff, 0xff).ToRgb().Should().Be(0xffffff); + } + + [Fact] + public void WithAlpha_Test() + { + // Act & assert + Color.FromArgb(255, 0x12, 0x34, 0x56).WithAlpha(128).A.Should().Be(128); + Color.FromArgb(255, 0x12, 0x34, 0x56).WithAlpha(128).R.Should().Be(0x12); + Color.FromArgb(255, 0x12, 0x34, 0x56).WithAlpha(128).G.Should().Be(0x34); + Color.FromArgb(255, 0x12, 0x34, 0x56).WithAlpha(128).B.Should().Be(0x56); + Color.FromArgb(0, 0xff, 0xff, 0xff).WithAlpha(255).A.Should().Be(255); + } +} diff --git a/PowerKit/Extensions/ColorExtensions.cs b/PowerKit/Extensions/ColorExtensions.cs new file mode 100644 index 0000000..83d7c3a --- /dev/null +++ b/PowerKit/Extensions/ColorExtensions.cs @@ -0,0 +1,29 @@ +#nullable enable +using System.Diagnostics.CodeAnalysis; +using System.Drawing; + +namespace PowerKit.Extensions; + +#if !POWERKIT_INCLUDE_COVERAGE +[ExcludeFromCodeCoverage] +#endif +internal static class ColorExtensions +{ + extension(Color color) + { + /// + /// Returns the hexadecimal representation of the color (e.g., #RRGGBB). + /// + public string ToHexString() => $"#{color.R:X2}{color.G:X2}{color.B:X2}"; + + /// + /// Returns the RGB value of the color as a 32-bit integer (without the alpha channel). + /// + public int ToRgb() => color.ToArgb() & 0xffffff; + + /// + /// Returns a new with the specified alpha value. + /// + public Color WithAlpha(int alpha) => Color.FromArgb(alpha, color); + } +}