美文网首页
swift3.1 UIColor扩展

swift3.1 UIColor扩展

作者: George2016 | 来源:发表于2017-06-02 13:28 被阅读31次
extension UIColor {
    
        convenience init(_ color: Any) {
        switch color {
        
        case let hex as Int: //16进制整型
            let intr = (hex >> 16) & 0xFF
            let intg = (hex >> 8) & 0xFF
            let intb = (hex) & 0xFF
            self.init(red: CGFloat(intr)/255, green: CGFloat(intg)/255, blue: CGFloat(intb)/255, alpha: 1)
        
        case let hex as String: //字符串
            var cString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()
            
            if (cString.hasPrefix("#")) {
                let index = cString.index(cString.startIndex, offsetBy:1)
                cString = cString.substring(from: index)
            }
            
            if (cString.characters.count != 6) {
                self.init(red: 1, green: 0, blue: 0, alpha: 1)
            }
            else {
                let rIndex = cString.index(cString.startIndex, offsetBy: 2)
                let rString = cString.substring(to: rIndex)
                let otherString = cString.substring(from: rIndex)
                let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
                let gString = otherString.substring(to: gIndex)
                let bIndex = cString.index(cString.endIndex, offsetBy: -2)
                let bString = cString.substring(from: bIndex)
                
                var intr:UInt32 = 0, intg:UInt32 = 0, intb:UInt32 = 0;
                Scanner(string: rString).scanHexInt32(&intr)
                Scanner(string: gString).scanHexInt32(&intg)
                Scanner(string: bString).scanHexInt32(&intb)
                
                self.init(red: CGFloat(intr)/255.0, green: CGFloat(intg)/255.0, blue: CGFloat(intb)/255.0, alpha: 1)
            }
        
        default:
            self.init(red: 1, green: 0, blue: 0, alpha: 1)
            break
        }
    }
}

相关文章

网友评论

      本文标题:swift3.1 UIColor扩展

      本文链接:https://www.haomeiwen.com/subject/vpcufxtx.html