Last active
May 29, 2019 04:33
-
-
Save adamgraham/35448fef73350559fd6aa5b56ab9dfdb to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from YPbPr 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 Y′PbPr colors. | |
extension UIColor { | |
/// The Rec.601 (standard-definition) coefficients used to calculate luma. | |
private static let encoding: (r: CGFloat, g: CGFloat, b: CGFloat) = (0.299, 0.587, 0.114) | |
/// The Y′PbPr components of a color - luma (Y′) and chroma (Pb,Pr). | |
struct YPbPr: Hashable { | |
/// The luma component of the color, in the range [0, 1] (black to white). | |
var Y: CGFloat | |
/// The blue-difference chroma component of the color, in the range [-0.5, 0.5]. | |
var Pb: CGFloat | |
/// The red-difference chroma component of the color, in the range [-0.5, 0.5]. | |
var Pr: CGFloat | |
} | |
/// The Y′PbPr components of the color using Rec.601 (standard-definition) encoding. | |
var yPbPr: YPbPr { | |
var (r, g, b) = (CGFloat(), CGFloat(), CGFloat()) | |
getRed(&r, green: &g, blue: &b, alpha: nil) | |
let k = UIColor.encoding | |
let Y = (k.r * r) + (k.g * g) + (k.b * b) | |
let Pb = 0.5 * ((b - Y) / (1.0 - k.b)) | |
let Pr = 0.5 * ((r - Y) / (1.0 - k.r)) | |
return YPbPr(Y: Y, Pb: Pb, Pr: Pr) | |
} | |
/// Initializes a color from Y′PbPr components. | |
/// - parameter yPbPr: The components used to initialize the color. | |
/// - parameter alpha: The alpha value of the color. | |
convenience init(_ yPbPr: YPbPr, alpha: CGFloat = 1.0) { | |
let Y = yPbPr.Y | |
let Pb = yPbPr.Pb | |
let Pr = yPbPr.Pr | |
let k = UIColor.encoding | |
let kr = (Pr * ((1.0 - k.r) / 0.5)) | |
let kgb = (Pb * ((k.b * (1.0 - k.b)) / (0.5 * k.g))) | |
let kgr = (Pr * ((k.r * (1.0 - k.r)) / (0.5 * k.g))) | |
let kb = (Pb * ((1.0 - k.b) / 0.5)) | |
let r = Y + kr | |
let g = Y - kgb - kgr | |
let b = Y + kb | |
self.init(red: r, green: g, blue: b, alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The digital equivalent of
YPbPr
isYCbCr
defined here: https://gist.github.com/adamgraham/0807893f1721056b279b40d3bd4e1e96