How can I create a UIColor from a hex string?

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

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

30条回答
  •  温柔的废话
    2020-11-22 17:20

    Swift equivalent of @Tom's answer, although receiving RGBA Int value to support transparency:

    func colorWithHex(aHex: UInt) -> UIColor
    {
        return UIColor(red: CGFloat((aHex & 0xFF000000) >> 24) / 255,
            green: CGFloat((aHex & 0x00FF0000) >> 16) / 255,
            blue: CGFloat((aHex & 0x0000FF00) >> 8) / 255,
            alpha: CGFloat((aHex & 0x000000FF) >> 0) / 255)
    }
    
    //usage
    var color = colorWithHex(0x7F00FFFF)
    

    And if you want to be able to use it from string you could use strtoul:

    var hexString = "0x7F00FFFF"
    
    let num = strtoul(hexString, nil, 16)
    
    var colorFromString = colorWithHex(num)
    

提交回复
热议问题