Created
December 28, 2016 18:18
-
-
Save fpg1503/afc358bf3f138e1964fbc26f409848d4 to your computer and use it in GitHub Desktop.
ColorExporter
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
// ([^#\n]*)\s#([\dA-F]{6}) | |
// (name: "$1", color: UIColor(hex: 0x$2)), | |
typealias NamedColor = (name: String, color: UIColor) | |
extension CGFloat { | |
var prettyString: String { | |
let formatter = NumberFormatter() | |
formatter.numberStyle = .decimal | |
formatter.roundingMode = .halfUp | |
formatter.maximumFractionDigits = 10 | |
return formatter.string(from: NSNumber(value: Double(self)))! | |
} | |
} | |
extension UIColor { | |
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { | |
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 | |
getRed(&r, green: &g, blue: &b, alpha: &a) | |
return (red: r, green: g, blue: b, alpha: a) | |
} | |
var colorLiteral: String { | |
let (r, g, b, a) = components | |
return "#colorLiteral(red: \(r.prettyString), green: \(g.prettyString), blue: \(b.prettyString), alpha: \(a.prettyString))" | |
} | |
convenience init(red: Int, green: Int, blue: Int) { | |
assert(red >= 0 && red <= 255, "Invalid red component") | |
assert(green >= 0 && green <= 255, "Invalid green component") | |
assert(blue >= 0 && blue <= 255, "Invalid blue component") | |
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) | |
} | |
convenience init(hex: Int) { | |
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff) | |
} | |
var hexValue: String { | |
let (r, g, b, a) = components | |
guard a == 1 else { fatalError("Do not use semi-transparent colors") } | |
let red = Int(r * 255) | |
let green = Int(g * 255) | |
let blue = Int(b * 255) | |
return String(format: "%02X%02X%02X", red, green, blue) | |
} | |
} | |
func function(_ namedColor: NamedColor) -> String { | |
return " class var \(namedColor.name): UIColor { return \(namedColor.color.colorLiteral) } //#\(namedColor.color.hexValue)" | |
} | |
func export(colors: [NamedColor]) -> String { | |
let header = "extension UIColor {\n" | |
let functions = colors.map(function).joined(separator: "\n") | |
let footer = "\n}" | |
return [header, functions, footer].joined() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment