Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions PowerKit.Tests/Extensions/ColorExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
29 changes: 29 additions & 0 deletions PowerKit/Extensions/ColorExtensions.cs
Original file line number Diff line number Diff line change
@@ -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)
{
/// <summary>
/// Returns the hexadecimal representation of the color (e.g., <c>#RRGGBB</c>).
/// </summary>
public string ToHexString() => $"#{color.R:X2}{color.G:X2}{color.B:X2}";

/// <summary>
/// Returns the RGB value of the color as a 32-bit integer (without the alpha channel).
/// </summary>
public int ToRgb() => color.ToArgb() & 0xffffff;

/// <summary>
/// Returns a new <see cref="Color" /> with the specified alpha value.
/// </summary>
public Color WithAlpha(int alpha) => Color.FromArgb(alpha, color);
}
}