UIColor to Hexadecimal (web color)

后端 未结 5 1407
悲&欢浪女
悲&欢浪女 2021-02-15 23:37

Is there an easy way to convert UIColor to a hexadecimal value ?
Or do we have to get the RGB components with CGColorGetComponents and then work it

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-16 00:27

    This is how I do did it with Swift 3:

    extension UIColor {
        var hex:String{
            get{
                var red:CGFloat = 0
                var blue:CGFloat = 0
                var green:CGFloat = 0
                var alpha:CGFloat = 0
    
                self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
                let rgb:Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0
                return String.localizedStringWithFormat("#%06x", rgb)
            }
        }
    }
    

    Or you can make it a method. I just like how color.hex looks vs color.hex().

提交回复
热议问题