Create a gist now

Instantly share code, notes, and snippets.

Embed
Mix UIColor and NSColor using hexadecimal codes
#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)
}
}
#elseif os(watchOS)
import WatchKit
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)
}
}
#elseif os(tvOS)
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]?) {
switch (components ?? []).count {
case 4: // RGB
self = (Int(components![0] * 255.0) << 16) + (Int(components![1] * 255) << 8) + (Int(components![2] * 255) << 0)
case 2: // Grayscale
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