Created
June 13, 2014 13:57
-
-
Save spllr/73650f57158db94d6124 to your computer and use it in GitHub Desktop.
Convert a hex string to SKColor
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 | |
import SpriteKit | |
extension String { | |
func hexComponents() -> String?[] { | |
let code = self | |
let offset = code.hasPrefix("#") ? 1 : 0 | |
let start: String.Index = code.startIndex | |
return [ | |
code[advance(start, offset)..advance(start, offset + 2)], | |
code[advance(start, offset + 2)..advance(start, offset + 4)], | |
code[advance(start, offset + 4)..advance(start, offset + 6)] | |
] | |
} | |
} | |
extension SKColor { | |
class func fromHexCode(code: String, alpha: Double = 1.0) -> SKColor { | |
let rgbValues = code.hexComponents().map { | |
(component: String?) -> CGFloat in | |
if let hex = component { | |
var rgb: CUnsignedInt = 0 | |
if NSScanner(string: hex).scanHexInt(&rgb) { | |
return CGFloat(rgb) / 255.0 | |
} | |
} | |
return 0.0 | |
} | |
return SKColor(red: rgbValues[0], green: rgbValues[1], blue: rgbValues[2], alpha: 1.0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment