Skip to content

Instantly share code, notes, and snippets.

@adamgraham
Last active May 27, 2019 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamgraham/dade138bcb414c454606978f4ff2e05c to your computer and use it in GitHub Desktop.
Save adamgraham/dade138bcb414c454606978f4ff2e05c to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from HSB (hue, saturation, brightness) colors.
/// An extension to provide conversion to and from HSB (hue, saturation, brightness) colors.
extension UIColor {
/// The HSB (hue, saturation, brightness) components of a color.
struct HSB: Hashable {
/// The hue component of the color, in the range [0, 360°].
var hue: CGFloat
/// The saturation component of the color, in the range [0, 100%].
var saturation: CGFloat
/// The brightness component of the color, in the range [0, 100%].
var brightness: CGFloat
}
/// The HSB (hue, saturation, brightness) components of the color.
var hsb: HSB {
var (h, s, b) = (CGFloat(), CGFloat(), CGFloat())
getHue(&h, saturation: &s, brightness: &b, alpha: nil)
return HSB(hue: h * 360.0,
saturation: s * 100.0,
brightness: b * 100.0)
}
/// Initializes a color from HSB (hue, saturation, brightness) components.
/// - parameter hsb: The components used to initialize the color.
/// - parameter alpha: The alpha value of the color.
convenience init(_ hsb: HSB, alpha: CGFloat = 1.0) {
self.init(hue: hsb.hue / 360.0,
saturation: hsb.saturation / 100.0,
brightness: hsb.brightness / 100.0,
alpha: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment