Skip to content

Instantly share code, notes, and snippets.

@spllr
Created June 13, 2014 13:57
Show Gist options
  • Save spllr/73650f57158db94d6124 to your computer and use it in GitHub Desktop.
Save spllr/73650f57158db94d6124 to your computer and use it in GitHub Desktop.
Convert a hex string to SKColor
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