Skip to content

Instantly share code, notes, and snippets.

@artemnovichkov
Last active January 30, 2017 02:15
Show Gist options
  • Save artemnovichkov/d04352a2986711e37265236a84082f77 to your computer and use it in GitHub Desktop.
Save artemnovichkov/d04352a2986711e37265236a84082f77 to your computer and use it in GitHub Desktop.
Elegant enum for custom colors worked on both iOS and macOS
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
fileprivate struct ColorComponents {
let first: CGFloat
let second: CGFloat
let third: CGFloat
let alpha: CGFloat
let model: ColorModel
init(first: CGFloat, second: CGFloat, third: CGFloat, alpha: CGFloat = 1, colorModel: ColorModel = .rgb) {
self.first = first
self.second = second
self.third = third
self.alpha = alpha
self.model = colorModel
}
}
fileprivate enum ColorModel {
case rgb, hsb
}
extension ColorComponents {
static var red = ColorComponents(first: 255, second: 0, third: 0)
static var green = ColorComponents(first: 0, second: 255, third: 0)
static var blue = ColorComponents(first: 0, second: 0, third: 255)
}
enum ColorSet {
#if os(iOS)
typealias Color = UIColor
#elseif os(OSX)
typealias Color = NSColor
#endif
static let red = color(for: .red)
static let green = color(for: .green)
static let blue = color(for: .blue)
// MARK: - Private
private static func color(for components: ColorComponents) -> Color {
switch components.model {
case .rgb:
let divider: CGFloat = 255
return Color(red: components.first / divider,
green: components.second / divider,
blue: components.third / divider,
alpha: components.alpha)
case .hsb:
return Color(hue: components.first,
saturation: components.second,
brightness: components.third,
alpha: components.alpha)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment