-
-
Save hstdt/12cccea7a51568a97dbceb014d4bf61a to your computer and use it in GitHub Desktop.
Color Descriptor
This file contains hidden or 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
enum ColorDescriptor { | |
case PatternImage(imageName: String) | |
case RGB(r: Int, g: Int, b: Int, a: Int) | |
} | |
extension ColorDescriptor : StringLiteralConvertible, RawRepresentable, Equatable { | |
typealias RawValue = StringLiteralType | |
typealias ExtendedGraphemeClusterLiteralType = StringLiteralType | |
typealias UnicodeScalarLiteralType = StringLiteralType | |
var color: UIColor { | |
switch self { | |
case let .PatternImage(imageName: imageName): | |
let image = UIImage(named: imageName)! | |
return UIColor(patternImage: image) | |
case let .RGB(r: ri, g: gi, b: bi, a: ai): | |
let r = CGFloat(ri) | |
let g = CGFloat(gi) | |
let b = CGFloat(bi) | |
let a = CGFloat(ai) | |
return UIColor(red: r / 255, green: g / 255, blue: b / 255, alpha: a / 255) | |
} | |
} | |
var rawValue: RawValue { | |
switch self { | |
case let .PatternImage(imageName: imageName): | |
return imageName | |
case let .RGB(r: r, g: g, b: b, a: a): | |
return "\(r),\(g),\(b),\(a)" | |
} | |
} | |
// MARK: Initializers | |
init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { | |
self.init(value) | |
} | |
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { | |
self.init(value) | |
} | |
init(stringLiteral value: StringLiteralType) { | |
self.init(value) | |
} | |
init?(rawValue: RawValue) { | |
self.init(rawValue) | |
} | |
init(_ string: String) { | |
let rgbComponents = string.componentsSeparatedByString(",") | |
.flatMap { Int($0) } | |
if rgbComponents.count == 4 { | |
self = .RGB(r: rgbComponents[0], g: rgbComponents[1], b: rgbComponents[2], a: rgbComponents[3]) | |
} else if let _ = UIImage(named: string) { | |
self = .PatternImage(imageName: string) | |
} else { | |
fatalError("Unrecognized color literal! Use format `r,g,b,a` on 255 scale, or a valid UIImage name") | |
} | |
} | |
} | |
func ==(lhs: ColorDescriptor, rhs: ColorDescriptor) -> Bool { | |
return lhs.rawValue == rhs.rawValue | |
} | |
enum ColorPalette : ColorDescriptor { | |
case White = "254,216,130,255" | |
case Green = "60,132,86,255" | |
case DarkGreen = "51,58,24,255" | |
case DarkGray = "64,48,56,255" | |
case ReddishOrange = "161,43,39,255" | |
case Red = "201,39,59,255" | |
case DarkRed = "103,5,2,255" | |
case SparklyWhite = "white_christmas_bg" | |
case SparklyRed = "red_christmas_bg" | |
case TexturedBackground = "texturedBackground" | |
var color: UIColor { | |
return rawValue.color | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment