Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active November 6, 2022 19:56
Show Gist options
  • Save cecilemuller/a06c4fc5b613829a4b63590ce29bac22 to your computer and use it in GitHub Desktop.
Save cecilemuller/a06c4fc5b613829a4b63590ce29bac22 to your computer and use it in GitHub Desktop.
CSS HSL "linear-gradient" to Swift "CAGradientLayer"
// CSS gradient generated by https://www.joshwcomeau.com/gradient-generator/
// hsl(199deg 95% 55%) 0%
// hsl(140deg 63% 65%) 50%
// hsl(99deg 100% 50%) 100%
let gradient = CAGradientLayer()
// ...
gradient.type = .axial
gradient.colors = [
UIColor.hsl(degrees: 199, saturation: 0.95, lightness: 0.55).cgColor,
UIColor.hsl(degrees: 140, saturation: 0.63, lightness: 0.65).cgColor,
UIColor.hsl(degrees: 99, saturation: 1.00, lightness: 0.50).cgColor
]
gradient.locations = [0, 0.5, 1]
import UIKit
extension UIColor {
static func hsl(hue h: CGFloat, saturation s: CGFloat, lightness l: CGFloat, alpha a: CGFloat = 1.0) -> UIColor {
var saturation: CGFloat = 0.0
let brightness = l + s * min(l, 1 - l)
if brightness == 0 {
saturation = 0.0
} else {
saturation = 2 * (1 - l / brightness)
}
return UIColor(hue: h, saturation: saturation, brightness: brightness, alpha: a)
}
static func hsl(degrees deg: CGFloat, saturation s: CGFloat, lightness l: CGFloat, alpha a: CGFloat = 1.0) -> UIColor {
return UIColor.hsl(hue: deg / 360, saturation: s, lightness: l, alpha: a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment