Skip to content

Instantly share code, notes, and snippets.

@adamgraham
Last active May 7, 2024 06:33
Show Gist options
  • Save adamgraham/3c0da2a452138e76b5dab2fa0ce9af3b to your computer and use it in GitHub Desktop.
Save adamgraham/3c0da2a452138e76b5dab2fa0ce9af3b to your computer and use it in GitHub Desktop.
An extension of the iOS class UIColor to provide conversion to and from CMYK (cyan, magenta, yellow, black) colors.
/// An extension to provide conversion to and from CMYK (cyan, magenta, yellow, black) colors.
extension UIColor {
/// The CMYK (cyan, magenta, yellow, black) components of a color, in the range [0, 100%].
struct CMYK: Hashable {
/// The cyan component of the color, in the range [0, 100%].
var cyan: CGFloat
/// The magenta component of the color, in the range [0, 100%].
var magenta: CGFloat
/// The yellow component of the color, in the range [0, 100%].
var yellow: CGFloat
/// The black component of the color, in the range [0, 100%].
var black: CGFloat
}
/// The CMYK (cyan, magenta, yellow, black) components of the color, in the range [0, 100%].
var cmyk: CMYK {
var (r, g, b) = (CGFloat(), CGFloat(), CGFloat())
getRed(&r, green: &g, blue: &b, alpha: nil)
let k = 1.0 - max(r, g, b)
var c = (1.0 - r - k) / (1.0 - k)
var m = (1.0 - g - k) / (1.0 - k)
var y = (1.0 - b - k) / (1.0 - k)
if c.isNaN { c = 0.0 }
if m.isNaN { m = 0.0 }
if y.isNaN { y = 0.0 }
return CMYK(cyan: c * 100.0,
magenta: m * 100.0,
yellow: y * 100.0,
black: k * 100.0)
}
/// Initializes a color from CMYK (cyan, magenta, yellow, black) components.
/// - parameter cmyk: The components used to initialize the color.
/// - parameter alpha: The alpha value of the color.
convenience init(_ cmyk: CMYK, alpha: CGFloat = 1.0) {
let c = cmyk.cyan / 100.0
let m = cmyk.magenta / 100.0
let y = cmyk.yellow / 100.0
let k = cmyk.black / 100.0
let r = (1.0 - c) * (1.0 - k)
let g = (1.0 - m) * (1.0 - k)
let b = (1.0 - y) * (1.0 - k)
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