【问题标题】:Converting rgb to hex in Swift在 Swift 中将 RGB 转换为十六进制
【发布时间】:2019-10-28 14:54:27
【问题描述】:

我正在尝试将我的 rgb 颜色转换为十六进制值。不幸的是,它总是返回 000000。这是我尝试过的代码:

let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())

let hexValue = String(format:"%02X", red) + String(format:"%02X", green) + String(format:"%02X", blue)

【问题讨论】:

    标签: swift hex rgb


    【解决方案1】:

    这里是生成 3 个随机数并将它们转换为十六进制字符串的更好方法:

    let red = Int.random(in: 0...255)
    let green = Int.random(in: 0...255)
    let blue = Int.random(in: 0...255)
    let hex = String(format:"%02X%02X%02X", red, green, blue)
    

    您的代码不起作用的原因是您的数字是CGFloat,介于 0.0 到 1.0 之间。但是您的字符串格式将它们视为Int 值。

    除此之外,drand48 的使用要求您先播种它们。

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2015-01-31
      • 2018-01-21
      • 2021-03-22
      • 2018-01-17
      • 2015-06-21
      相关资源
      最近更新 更多