Skip to content

Commit

Permalink
Merge pull request #1 from skagedal/master
Browse files Browse the repository at this point in the history
Make random background color deterministic for a specific name
  • Loading branch information
bachonk committed Aug 11, 2017
2 parents 92b2795 + 5ecbf34 commit ee71c45
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions InitialsImageView.swift
Original file line number Diff line number Diff line change
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

0 comments on commit ee71c45

Please sign in to comment.