Swift: convert string to hex color code

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

I have found several solutions on how to draw a UIColor with a hex color code, but I am not quite clear how I could generate a hex color code (#ffffff) from a string like the one above. Any help would be appreciated, thanks.

+3


source to share


2 answers


There are too many user IDs to get a unique color for every possible user ID. Your best bet is to find a way to narrow each user ID down to one of the possible colors available and accept the fact that two users can have the same color.

One possible solution is to get the hashValue

user ID string string and then reduce that Int

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 moment, the colorNum

range 0

is -0xFFFFFF



Now you can 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 want to keep this color in the user profile as it is hashValue

not guaranteed to be the same every time you start the application.

+11


source


As I understand it, you are trying to generate a random color for each user every time and store it in Firebase? Correct me if I am wrong.

I hope this solution solves your problem of generating random colors every time. In short, wherever and whenever you need a random unique color - call the method and check if the returned UIColor is not found in the database. If it doesn't exist, use it!



func getRandomColor() -> UIColor {
let randomRed:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomGreen:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
let randomBlue:CGFloat = CGFloat(arc4random()) / CGFloat(UInt32.max)
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}

      

I hope the above solution from Oscar De Moya from https://classictutorials.com/2014/08/generate-a-random-color-in-swift/ helps you.

0


source







All Articles