From ced1c0227ecd1151f8dcabd5872f662bd4de389c Mon Sep 17 00:00:00 2001 From: Nor Khasyatillah Date: Wed, 17 Jul 2024 14:38:37 +0700 Subject: [PATCH] add Clamp() --- CHANGELOG.md | 8 +++++++- colorparser.go | 7 +++++++ colorparser_test.go | 6 ++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 589e1f2..8266a35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/colorparser.go b/colorparser.go index a60c858..7e4ef9b 100644 --- a/colorparser.go +++ b/colorparser.go @@ -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() diff --git a/colorparser_test.go b/colorparser_test.go index 7f8d9d0..35b9b4e 100644 --- a/colorparser_test.go +++ b/colorparser_test.go @@ -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")