Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Created August 23, 2017 07:48
Show Gist options
  • Save HarshilShah/dbd00039f866a4f325dfdb09927a3320 to your computer and use it in GitHub Desktop.
Save HarshilShah/dbd00039f866a4f325dfdb09927a3320 to your computer and use it in GitHub Desktop.
Initialise Display P3 UIColors using HSBA values
import UIKit
extension UIColor {
convenience init(displayP3Hue hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat = 1) {
// Bound colours to range of [0–1]
let newHue = max(0, min(1, hue))
let newSaturation = max(0, min(1, saturation))
let newBrightness = max(0, min(1, brightness))
let newAlpha = max(0, min(1, alpha))
// Instantiate regular HSBA colour
let hsbaColor = UIColor(hue: newHue, saturation: newSaturation, brightness: newBrightness, alpha: newAlpha)
// Extract corresponding RGBA values and instantiate wide colour
var (red, green, blue, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0)
// Can this fail? Dunno.
_ = hsbaColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
self.init(displayP3Red: red, green: green, blue: blue, alpha: alpha)
}
}
let rgbaValues: (CGFloat, CGFloat, CGFloat, CGFloat) = (178/255, 055/255, 176/255, 1)
let hsbaValues: (CGFloat, CGFloat, CGFloat, CGFloat) = (301/360, 069/100, 070/100, 1)
let randomRGBA = UIColor(red: rgbaValues.0, green: rgbaValues.1, blue: rgbaValues.2, alpha: rgbaValues.3)
let randomHSBA = UIColor(hue: hsbaValues.0, saturation: hsbaValues.1, brightness: hsbaValues.2, alpha: hsbaValues.3)
let displayP3RandomRGBA = UIColor(displayP3Red: rgbaValues.0, green: rgbaValues.1, blue: rgbaValues.2, alpha: rgbaValues.3)
let displayP3RandomHSBA = UIColor(displayP3Hue: hsbaValues.0, saturation: hsbaValues.1, brightness: hsbaValues.2, alpha: hsbaValues.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment