Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Convert string to hex color code

Tags:

swift

I have generated user Ids (with a format like ""XzSYoKJaqKYREkdB2dgwt0fLOPP2"") from a database that I would like to use to create an UIColor.

I found several solutions on how to crate an UIColor with a color hex code, but I don't quite know how I would generate a color hex code (#ffffff) from a string like the one above. Any help would be appreciated, thanks.

like image 780
José Avatar asked Dec 05 '22 15:12

José


1 Answers

There are far too many user ids to get a unique color for every possible user id. Your best option would be to find a way to narrow down each user id to one of the possible available colors and accept the fact that two users may have the same color.

One possible solution is would be to get the hashValue of the user id string and then reduce that Int down to one of the possible 16,777,216 colors.

let userId = "XzSYoKJaqKYREkdB2dgwt0fLOPP2" // or whatever the id is
let hash = abs(userId.hashValue)
let colorNum = hash % (256*256*256)

At this point colorNum is the range 0 - 0xFFFFFF

You can now create a color from colorNum.

let red = colorNum >> 16
let green = (colorNum & 0x00FF00) >> 8
let blue = (colorNum & 0x0000FF)
let userColor = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)

You will want to store this color in the user's profile since the hashValue isn't guaranteed to be the same each time your app runs.

like image 162
rmaddy Avatar answered Dec 30 '22 01:12

rmaddy