Created
November 9, 2014 12:25
-
-
Save hansott/c4b9151920097be70f39 to your computer and use it in GitHub Desktop.
SKColor extension: create SKColor from hex value
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 Foundation | |
import SpriteKit | |
import UIKit | |
extension SKColor { | |
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 index = advance(rgba.startIndex, 1) | |
let hex = rgba.substringFromIndex(index) | |
let scanner = NSScanner(string: hex) | |
var hexValue: CUnsignedLongLong = 0 | |
if scanner.scanHexLongLong(&hexValue) { | |
if countElements(hex) == 6 { | |
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 | |
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 | |
blue = CGFloat(hexValue & 0x0000FF) / 255.0 | |
} else if countElements(hex) == 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) | |
} | |
} | |
// How to use | |
var color = SKColor(rgba: "#545454") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment