Skip to content

Instantly share code, notes, and snippets.

@cegiela
Created March 17, 2017 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cegiela/b9a8833977be26950a901f7b1438cb56 to your computer and use it in GitHub Desktop.
Save cegiela/b9a8833977be26950a901f7b1438cb56 to your computer and use it in GitHub Desktop.
Just the code for repeatably hashing a string into a color
//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