我想为每个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)
}
在评论中,您提到只需要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)
}
关于ios - 如何在Swift中为每个UUID生成随机但唯一的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59027863/