Skip to content

Commit

Permalink
feat(ad-hoc): minor improvements (#346)
Browse files Browse the repository at this point in the history
* Set `swiftLanguageVersions` in package spec
* Improve color lightness calculation
  • Loading branch information
andrii-vysotskyi-cko authored Sep 10, 2024
1 parent 955f152 commit d7c660b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
3 changes: 2 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,6 @@ let package = Package(
.process("Resources")
]
)
]
],
swiftLanguageVersions: [.v5]
)
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,45 @@ import SwiftUI

extension UIColor {

func isLight(threshold: CGFloat = 0.5) -> Bool? {
perceptualLightness.map { $0 > threshold }
}

// MARK: - Private Methods

/// Returns the relative luminance of this color in range [0, 1].
///
/// - NOTE: Alpha is ignored
var brightness: CGFloat? {
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)! // swiftlint:disable:this force_unwrapping
let convertedColor = cgColor.converted(
to: colorSpace, intent: .defaultIntent, options: nil
)
private var perceptualLightness: CGFloat? {
guard let luminance else {
return nil
}
if luminance <= 0.008856 { // Based on CIE standard
return luminance * 9.033
}
return pow(luminance, 1 / 3) * 1.16 - 0.16
}

private var luminance: CGFloat? {
// swiftlint:disable:next force_unwrapping
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
let convertedColor = cgColor.converted(to: colorSpace, intent: .defaultIntent, options: nil)
guard let components = convertedColor?.components, components.count >= 3 else {
return nil
}
// Calculation is based on this https://www.w3.org/WAI/ER/WD-AERT/#color-contrast
return (components[0] * 299 + components[1] * 587 + components[2] * 114) / 1000
// swiftlint:disable identifier_name
let r = linearValue(ofGammaEncoded: components[0])
let g = linearValue(ofGammaEncoded: components[1])
let b = linearValue(ofGammaEncoded: components[2])
// swiftlint:enable identifier_name
return 0.2126 * r + 0.7152 * g + 0.0722 * b
}

func isLight(threshold: CGFloat = 0.5) -> Bool? {
brightness.map { $0 > threshold }
/// Convert a gamma encoded RGB to a linear value.
private func linearValue(ofGammaEncoded component: CGFloat) -> CGFloat {
if component <= 0.04045 {
return component / 12.92
}
return pow((component + 0.055) / 1.055, 2.4)
}
}

0 comments on commit d7c660b

Please sign in to comment.