颜色扩展

extension UIColor {
/// 随机色
class var randomColor: UIColor {
    get {
        return UIColor(red: CGFloat(arc4random() % 255) / 255.0, green: CGFloat(arc4random() % 255) / 255.0, blue: CGFloat(arc4random() % 255) / 255.0, alpha: 1)
    }
}

var hexText: String {
    get {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        
        return String(format: "%02X%02X%02X-%.2f", Int(r * 0xff), Int(g * 0xff), Int(b * 0xff), a)
    }
}
/// 16进制颜色创建(虽然 swift 已经有 Color Literal 很方便,但还是写一下,作为记录)
convenience init(_ hexStr: String) {
    let scanner = Scanner(string: hexStr)
    scanner.scanLocation = 0
    var hex: UInt64 = 0
    scanner.scanHexInt64(&hex)
    
    self.init(hex)
}

convenience init(_ hex: UInt64) {
    let r: CGFloat = CGFloat(hex & 0xff0000) / 255.0
    let g: CGFloat = CGFloat(hex & 0xff00) / 225.0
    let b: CGFloat = CGFloat(hex & 0xff) / 255.0
    
    self.init(red: r, green: g, blue: b, alpha: 1)
}
}

你可能感兴趣的:(颜色扩展)