Last active
August 29, 2015 14:04
-
-
Save venj/8dcd5f97cbff293636f4 to your computer and use it in GitHub Desktop.
A UIColor Extension to parse Hex string(for CSS and for KML) to color. Code works for Xcode 6 Beta 5. Based on https://github.com/yeahdongcn/UIColor-Hex-Swift/blob/master/UIColorExtension.swift
This file contains 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
import UIKit | |
extension UIColor { | |
convenience init(kmlColorString:String) { | |
var scanner = NSScanner(string:kmlColorString) | |
var color:UInt32 = 0; | |
scanner.scanHexInt(&color) | |
let mask:UInt32 = 0x000000FF | |
var a = color >> 24 & mask | |
var b = color >> 16 & mask | |
var g = color >> 8 & mask | |
var r = color & mask | |
var red = CGFloat(r) / 255.0 | |
var green = CGFloat(g) / 255.0 | |
var blue = CGFloat(b) / 255.0 | |
var alpha = CGFloat(a) / 255.0 | |
self.init(red:red, green:green, blue:blue, alpha:alpha) | |
} | |
convenience init(rgba: String) { | |
var red: CGFloat = 0.0 | |
var green: CGFloat = 0.0 | |
var blue: CGFloat = 0.0 | |
var alpha: CGFloat = 1.0 | |
if rgba.hasPrefix("#") { | |
let hex = rgba.substringFromIndex(advance(rgba.startIndex, 1)) | |
let scanner = NSScanner.scannerWithString(hex) | |
var hexValue: CUnsignedLongLong = 0 | |
if scanner.scanHexLongLong(&hexValue) { | |
if (hex as NSString).length == 6 { | |
red = CGFloat(hexValue & 0xFF0000 >> 16) / 255.0 | |
green = CGFloat(hexValue & 0x00FF00 >> 8) / 255.0 | |
blue = CGFloat(hexValue & 0x0000FF) / 255.0 | |
} else if (hex as NSString).length == 8 { | |
red = CGFloat(hexValue & 0xFF000000 >> 24) / 255.0 | |
green = CGFloat(hexValue & 0x00FF0000 >> 16) / 255.0 | |
blue = CGFloat(hexValue & 0x0000FF00 >> 8) / 255.0 | |
alpha = CGFloat(hexValue & 0x000000FF) / 255.0 | |
} else { | |
print("invalid rgb string, length should be 7 or 9") | |
} | |
} else { | |
println("scan hex error") | |
} | |
} else { | |
print("invalid rgb string, missing '#' as prefix") | |
} | |
self.init(red:red, green:green, blue:blue, alpha:alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment