Last active
January 18, 2020 16:29
-
-
Save anoop4real/c88af858e7101d3d42895b860baab94d to your computer and use it in GitHub Desktop.
A small utility to generate color hash from string for Swift and also generate UIColor
This file contains hidden or 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 UIKit | |
func generateColorFor(text: String) -> UIColor{ | |
var hash = 0 | |
let colorConstant = 131 | |
let maxSafeValue = Int.max / colorConstant | |
for char in text.unicodeScalars{ | |
if hash > maxSafeValue { | |
hash = hash / colorConstant | |
} | |
hash = Int(char.value) + ((hash << 5) - hash) | |
} | |
let finalHash = abs(hash) % (256*256*256); | |
//let color = UIColor(hue:CGFloat(finalHash)/255.0 , saturation: 0.40, brightness: 0.75, alpha: 1.0) | |
let color = UIColor(red: CGFloat((finalHash & 0xFF0000) >> 16) / 255.0, green: CGFloat((finalHash & 0xFF00) >> 8) / 255.0, blue: CGFloat((finalHash & 0xFF)) / 255.0, alpha: 1.0) | |
return color | |
} | |
var c = generateColorFor(text: "igjgjhgjhgjhgjhgjhgjhgjhgjhgjhgjkjhkhkjhjkhhkh kjkjhkjhkhkuubbjbjkkk") | |
// | |
var c1 = generateColorFor(text: "Anna Haro") | |
var c2 = generateColorFor(text: "Danny Davis ") | |
var c3 = generateColorFor(text: "Danny David") | |
var c4 = generateColorFor(text: "Donny") | |
var c5 = generateColorFor(text: "Donna") | |
var c6 = generateColorFor(text: "Shawn Mann") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment