osx - Get CGColor from Hex string in swift ( OS X ) -
i implementing first os x app , created cgcolor extension. there way cgcolor hex string ?
thanks !
here extension nscolor
hexstring
public extension nscolor { public convenience init?(hexstring: string) { self.init(hexstring: hexstring, alpha: 1.0) } public convenience init?(hexstring: string, alpha: float) { var hex = hexstring // check hash , remove hash if hex.hasprefix("#") { hex = hex.substringfromindex(hex.startindex.advancedby(1)) } if (hex.rangeofstring("(^[0-9a-fa-f]{6}$)|(^[0-9a-fa-f]{3}$)", options: .regularexpressionsearch) != nil) { // deal 3 character hex strings if hex.characters.count == 3 { let redhex = hex.substringtoindex(hex.startindex.advancedby(1)) let greenhex = hex.substringwithrange(range<string.index>(start: hex.startindex.advancedby(1), end: hex.startindex.advancedby(2))) let bluehex = hex.substringfromindex(hex.startindex.advancedby(2)) hex = redhex + redhex + greenhex + greenhex + bluehex + bluehex } let redhex = hex.substringtoindex(hex.startindex.advancedby(2)) let greenhex = hex.substringwithrange(range<string.index>(start: hex.startindex.advancedby(2), end: hex.startindex.advancedby(4))) let bluehex = hex.substringwithrange(range<string.index>(start: hex.startindex.advancedby(4), end: hex.startindex.advancedby(6))) var redint: cunsignedint = 0 var greenint: cunsignedint = 0 var blueint: cunsignedint = 0 nsscanner(string: redhex).scanhexint(&redint) nsscanner(string: greenhex).scanhexint(&greenint) nsscanner(string: bluehex).scanhexint(&blueint) self.init(red: cgfloat(redint) / 255.0, green: cgfloat(greenint) / 255.0, blue: cgfloat(blueint) / 255.0, alpha: cgfloat(alpha)) } else { // note: // swift 1.1 compiler unable destroy partially initialized classes in cases, // disallows formation of situation have to. consider bug fixed // in future releases, not feature. -- apple forum self.init() return nil } }
example:
let color: nscolor = nscolor(hexstring: "#ff8942").cgcolor
Comments
Post a Comment