Skip to content

Commit

Permalink
add Clamp()
Browse files Browse the repository at this point in the history
  • Loading branch information
mazznoer committed Jul 17, 2024
1 parent b0cad02 commit ced1c02
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# Changelog

## [Unreleased](https://github.com/mazznoer/csscolorparser/compare/v0.1.3...HEAD)
## [Unreleased](https://github.com/mazznoer/csscolorparser/compare/v0.1.4...HEAD)

### Added

- `Clamp()`

## v0.1.4

### Added

Expand Down
7 changes: 7 additions & 0 deletions colorparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ func (c Color) RGBA255() (r, g, b, a uint8) {
return
}

func (c *Color) Clamp() {
c.R = math.Max(math.Min(c.R, 1), 0)
c.G = math.Max(math.Min(c.G, 1), 0)
c.B = math.Max(math.Min(c.B, 1), 0)
c.A = math.Max(math.Min(c.A, 1), 0)
}

// HexString returns CSS hexadecimal string.
func (c Color) HexString() string {
r, g, b, a := c.RGBA255()
Expand Down
6 changes: 6 additions & 0 deletions colorparser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ func TestColor(t *testing.T) {
equalStr(t, c.HexString(), "#0000ff80")
equalStr(t, c.RGBString(), "rgba(0,0,255,0.5)")

c = Color{1.2001, 0.999, -0.001, 0.001}
c.Clamp()
if !isColorEqual(c, Color{1, 0.999, 0, 0.001}) {
t.Errorf("failed: %v", c)
}

c = FromHwb(0, 0, 0, 1)
equalStr(t, c.HexString(), "#ff0000")

Expand Down

0 comments on commit ced1c02

Please sign in to comment.