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
13 changes: 4 additions & 9 deletions Sources/HandySwiftUI/Extensions/ColorExt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ extension Color {
return self.change(attribute, to: self.hlco.chroma + addition)

case .opacity:
return self.change(attribute, to: self.hlco.opacity + addition)
return self.change(attribute, to: self.rgbo.opacity + addition)
}
}

Expand All @@ -516,13 +516,14 @@ extension Color {
/// - Returns: The resulting new `Color` with the specified change applied.
public func change(_ attribute: ChangeableAttribute, to newValue: Double) -> Self {
switch attribute {
case .red, .green, .blue:
case .red, .green, .blue, .opacity:
// Opacity is the same in every color space, so the RGB path changes it without a lossy round trip through HLC
return self.newRgboColor(attribute, newValue)

case .hueHSB, .saturation, .brightness:
return self.newHsboColor(attribute, newValue)

case .hueHLC, .luminance, .chroma, .opacity:
case .hueHLC, .luminance, .chroma:
return self.newHlcoColor(attribute, newValue)
}
}
Expand All @@ -540,9 +541,6 @@ extension Color {
case .chroma:
newHlco.chroma = newValue

case .opacity:
newHlco.opacity = newValue

default:
break
}
Expand All @@ -563,9 +561,6 @@ extension Color {
case .brightness:
newHsbo.brightness = newValue

case .opacity:
newHsbo.opacity = newValue

default:
break
}
Expand Down
17 changes: 17 additions & 0 deletions Tests/HandySwiftUITests/ColorExtTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,21 @@ struct ColorExtTests {
// An in-gamut Display P3 color must be converted, not reported with its raw P3 components (which would be "80CC4D")
#expect(Color(.displayP3, red: 0.5, green: 0.8, blue: 0.3).toHex() == "64CE2F")
}

@Test(arguments: [(1.0, 0.0, 0.5), (0.2, 0.4, 0.6), (0.0, 1.0, 0.0)])
func changingOpacityKeepsTheRGBComponents(red: Double, green: Double, blue: Double) {
let color = Color(red: red, green: green, blue: blue)

// Float precision of the platform colors allows for deviations around 1e-7, the HLC round trip caused around 1e-6
func expectSameRGB(_ changed: (red: Double, green: Double, blue: Double, opacity: Double), opacity: Double) {
let tolerance = 0.000_000_5
#expect(abs(changed.red - color.rgbo.red) < tolerance)
#expect(abs(changed.green - color.rgbo.green) < tolerance)
#expect(abs(changed.blue - color.rgbo.blue) < tolerance)
#expect(abs(changed.opacity - opacity) < tolerance)
}

expectSameRGB(color.change(.opacity, to: 0.5).rgbo, opacity: 0.5)
expectSameRGB(color.change(.opacity, by: -0.25).rgbo, opacity: 0.75)
}
}
Loading