Last active
November 1, 2021 19:24
-
-
Save adamgraham/263fac81705221a96e4719cb1ad36009 to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from linear RGB colors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// An extension to provide conversion to and from linear RGB colors. | |
extension UIColor { | |
/// A set of non-gamma corrected linear RGB values, in the range [0, 1]. | |
typealias LinearRGB = (r: CGFloat, g: CGFloat, b: CGFloat) | |
/// The inverse companded sRGB components to get non-gamma corrected linear values, | |
/// in the range [0, 1]. | |
var linearRGB: LinearRGB { | |
var (r, g, b) = (CGFloat(), CGFloat(), CGFloat()) | |
getRed(&r, green: &g, blue: &b, alpha: nil) | |
r = (r > 0.03928) ? pow((r + 0.055) / 1.055, 2.4) : (r / 12.92) | |
g = (g > 0.03928) ? pow((g + 0.055) / 1.055, 2.4) : (g / 12.92) | |
b = (b > 0.03928) ? pow((b + 0.055) / 1.055, 2.4) : (b / 12.92) | |
return (r, g, b) | |
} | |
/// Initializes an sRGB gamma corrected color from linear RGB values. | |
/// - parameter rgb: The linear RGB values to be gamma corrected. | |
/// - parameter alpha: The alpha value of the color. | |
convenience init(linear rgb: LinearRGB, alpha: CGFloat = 1.0) { | |
let k: CGFloat = 1.0 / 2.4 | |
let red = (rgb.r <= 0.00304) ? (12.92 * rgb.r) : (1.055 * pow(rgb.r, k) - 0.055) | |
let green = (rgb.g <= 0.00304) ? (12.92 * rgb.g) : (1.055 * pow(rgb.g, k) - 0.055) | |
let blue = (rgb.b <= 0.00304) ? (12.92 * rgb.b) : (1.055 * pow(rgb.b, k) - 0.055) | |
self.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment