How can I create a UIColor from a hex string?

后端 未结 30 1121
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  囚心锁ツ
    2020-11-22 17:16

    extension UIColor {
        convenience init(hexaString: String, alpha: CGFloat = 1) {
            let chars = Array(hexaString.dropFirst())
            self.init(red:   .init(strtoul(String(chars[0...1]),nil,16))/255,
                      green: .init(strtoul(String(chars[2...3]),nil,16))/255,
                      blue:  .init(strtoul(String(chars[4...5]),nil,16))/255,
                      alpha: alpha)}
    }
    

    Usage:

    let redColor       = UIColor(hexaString: "#FF0000")              // r 1,0 g 0,0 b 0,0 a 1,0
    let transparentRed = UIColor(hexaString: "#FF0000", alpha: 0.5)  // r 1,0 g 0,0 b 0,0 a 0,5
    

提交回复
热议问题