Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random but unique color for each UUID in Swift?

Tags:

xcode

ios

swift

I want to generate a random but unique UIColor for each UUID. Currently, I'm using this method but this method doesn't provide red/orange/yellow colours for ids. More specifically, I want to generate a colour scheme like WhatsApp group chat where each user has a unique title colour.

func getColorFromUUID(uuid:String) -> UIColor {
        var hexa = ""
        hexa += uuid.prefix(2)

        let indexMid = uuid.index(uuid.startIndex, offsetBy: uuid.count/2 + 1)
        let indexMidNext = uuid.index(uuid.startIndex, offsetBy: uuid.count/2 + 1)
        let mid = String.init(uuid[indexMid])
        let midNext = String.init(uuid[indexMidNext])
        hexa +=  mid
        hexa += midNext

        hexa += uuid.suffix(2)

        return self.hexStringToUIColor(hex: hexa)

    }

func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        }

        if ((cString.count) != 6) {
            return UIColor.gray
        }

        var rgbValue:UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }

like image 438
Omair Ahmed Avatar asked Sep 05 '25 03:09

Omair Ahmed


1 Answers

Here's a simple way to think about it, colours are essentially represented by the numbers between 0 and 0xffffff. To get a number between 0 and 0xffffff from a string, you can get the hash code of the string, and % 0x1000000. Then you can extract the RGBs with bit masks:

func color(forUUID uuid: String) -> UIColor {
    let hash = uuid.hash
    let colorCode = abs(hash) % 0x1000000
    let red = colorCode >> 16
    let green = (colorCode >> 8) & 0xff
    let blue = colorCode & 0xff
    return UIColor(red: CGFloat(red) / 256, green: CGFloat(green) / 256, blue: CGFloat(blue) / 256, alpha: 1)
}

enter image description here

In the comments, you mentioned that you only want 256 unique colours. In that case, % 256 will do. You then pass the result to the HSB initialiser for UIColor:

func color(forUUID uuid: String) -> UIColor {
    let hash = uuid.hash
    let hue = abs(hash) % 256
    return UIColor(hue: CGFloat(hue) / 256, saturation: 1, brightness: 1, alpha: 1)
}

enter image description here

like image 71
Sweeper Avatar answered Sep 07 '25 20:09

Sweeper