Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Mix UIColor and NSColor using hexadecimal codes
//
// © 2017 @toddheasley
//
#if os(macOS)
import Cocoa
extension NSColor: RGBHexCoding {
}
extension RGBHexCoding where Self: NSColor {
init(hex: Int, alpha: CGFloat = 1.0) {
self.init(red: hex.red, green: hex.green, blue: hex.blue, alpha: alpha)
}
var hex: Int {
return Int(components: cgColor.components)
}
}
#elseif os(iOS)
import UIKit
extension UIColor: RGBHexCoding {
}
extension RGBHexCoding where Self: UIColor {
init(hex: Int, alpha: CGFloat = 1.0) {
self.init(red: hex.red, green: hex.green, blue: hex.blue, alpha: alpha)
}
var hex: Int {
return Int(components: cgColor.components)
}
}
#endif
protocol RGBHexCoding {
init(hex: Int, alpha: CGFloat)
var hex: Int {
get
}
}
extension Int {
fileprivate init(components: [CGFloat]?) {
guard let components = components else {
self = 0
return
}
switch components.count {
case 4:
self = (Int(components[0] * 255.0) << 16) + (Int(components[1] * 255) << 8) + (Int(components[2] * 255) << 0)
case 2:
self = (Int(components[0] * 255) << 16) + (Int(components[0] * 255) << 8) + (Int(components[0] * 255) << 0)
default:
self = 0
}
}
fileprivate var red: CGFloat {
return CGFloat((self & 0xFF0000) >> 16) / 255.0
}
fileprivate var green: CGFloat {
return CGFloat((self & 0x00FF00) >> 8) / 255.0
}
fileprivate var blue: CGFloat {
return CGFloat(self & 0x00FF) / 255.0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment