ios - 如何在Swift中为每个UUID生成随机但唯一的颜色?

标签 ios swift xcode

我想为每个UUID生成一个随机但唯一的UIColor。目前,我正在使用此方法,但是此方法不提供ID的红色/橙色/黄色。更具体地说,我想生成一个类似于WhatsApp群聊的配色方案,其中每个用户都有唯一的标题颜色。

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)
        )
    }

最佳答案

这是一种简单的思考方式,颜色基本上由0到0xffffff之间的数字表示。要从字符串中获取介于0和0xffffff之间的数字,您可以获取字符串的哈希码和% 0x1000000。然后,您可以使用位掩码提取RGB:

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

在评论中,您提到只需要256种独特的颜色。在这种情况下,% 256将起作用。然后,将结果传递给HSB初始化程序以获取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

关于ios - 如何在Swift中为每个UUID生成随机但唯一的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59027863/

相关文章:

swift - 使用 guard 检查 nil 而不隐式展开

swift - 如何在 iOS 10.3 上从 UIBarButtonItem.appearance() 中删除标题

ios - 文件名包含特殊字符时无法下载文件

ios - 在 for 循环中使用 UIAlertViews 对 Xcode 中的数字求和

ios - UICollectionViewFlowLayout - 强制为某些项目换行

ios - Xcode 本地化 Main.strings 文件具有多个具有相同上下文的字符串。将所有内容链接到一个主字符串?

ios - iOS : Getting a strange error ever since I switch header requests library. -[__NSCFString objectForKey:]:

swift - 使用 Swift 从 NSData 中获取数据

ios - 无法通过手动安装来安装Mixpanel iOS SDK-找不到Mixpanel/Mixpanel.h文件

xcode - 我如何阅读仪器?