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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With