Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make random background color deterministic for a specific name #1

Merged
merged 1 commit into from Aug 11, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 5 additions & 4 deletions InitialsImageView.swift
Expand Up @@ -17,7 +17,7 @@ extension UIImageView {
public func setImageForName(string: String, backgroundColor: UIColor?, circular: Bool, textAttributes: [String: AnyObject]?) {

let initials: String = initialsFromString(string: string)
let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor()
let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor(for: string)
let attributes: [String: AnyObject] = (textAttributes != nil) ? textAttributes! : [
NSFontAttributeName: self.fontForFontName(name: nil),
NSForegroundColorAttributeName: UIColor.white
Expand Down Expand Up @@ -123,11 +123,12 @@ private func initialsFromString(string: String) -> String {

private func randomColorComponent() -> Int {
let limit = kColorMaxComponent - kColorMinComponent

return kColorMinComponent + Int(arc4random_uniform(UInt32(limit)))
return kColorMinComponent + Int(drand48() * Double(limit))
}

private func randomColor() -> UIColor {
private func randomColor(for string: String) -> UIColor {
srand48(string.hashValue)

let red = CGFloat(randomColorComponent()) / 255.0
let green = CGFloat(randomColorComponent()) / 255.0
let blue = CGFloat(randomColorComponent()) / 255.0
Expand Down