Created
March 17, 2017 16:34
-
-
Save cegiela/b9a8833977be26950a901f7b1438cb56 to your computer and use it in GitHub Desktop.
Just the code for repeatably hashing a string into a color
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
//Based on https://github.com/ngs/color-hash.swift | |
import UIKit | |
import XCPlayground | |
//magic numbers taken from original | |
let seed = CGFloat(131.0) | |
let seed2 = CGFloat(137.0) | |
let maxSafeInteger = 9007199254740991.0 / seed2 | |
let defaultLS = [CGFloat(0.35), CGFloat(0.5), CGFloat(0.65)] | |
let full = CGFloat(360.0) | |
var saturation = CGFloat(0.4) | |
var brightness = CGFloat(0.8) | |
var str = "Hello" | |
//break off each character and extract it's unicore scalar value (then math with magic numbers) | |
func hashFromString(string:String) -> CGFloat { | |
var hash = CGFloat(0) | |
for char in "\(string)x".characters { | |
if let scalarVal = String(char).unicodeScalars.first?.value { | |
if hash > maxSafeInteger { | |
hash = hash / seed2 | |
} | |
hash = hash * seed + CGFloat(scalarVal) | |
} | |
} | |
return hash | |
} | |
//bit more math to get hue, saturation, brightness | |
//truncatingRemainder(dividingBy:) is basically a % operation (#swiftThings) | |
func colorFromString(string:String) -> UIColor { | |
var hash = hashFromString(string: string) | |
let h = (hash.truncatingRemainder(dividingBy: (full - 1.0))) / full | |
hash /= full | |
let s = saturation | |
let b = brightness | |
return UIColor(hue: h, saturation: s, brightness: b, alpha: 1.0) | |
} | |
//mything.color = colorFromString(string: str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment