Created
July 26, 2016 21:38
-
-
Save scottdelly/1d06b278d7d1a12643466a6f2e64e8d2 to your computer and use it in GitHub Desktop.
A utility method to create a UIColor from an arbitrary string. Inspired by http://stackoverflow.com/a/16348977/2138077
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
func fromString(string: String) -> UIColor { | |
var hash = 0 | |
let utf16array = Array(string.utf16) | |
for i in 0..<utf16array.count { | |
hash = Int(utf16array[i]) + ((hash << 5) - hash) | |
} | |
var colorValues = [CGFloat]() | |
for i in 0..<3 { | |
let value = (hash >> (i * 8)) & 0xFF | |
colorValues.append((CGFloat(value)/255.0)) | |
} | |
return UIColor(red: colorValues[0], green: colorValues[1], blue: colorValues[2], alpha: 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fromString("greenish")