Swift3 十六进制颜色代码转UIColor & CGColor

前端之家收集整理的这篇文章主要介绍了Swift3 十六进制颜色代码转UIColor & CGColor前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这个算是常用的函数了 网上的都是swift2版本 自己更新了下在这里留个档

func colorWithHexString (hex:String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }
        
        if (cString.characters.count == 3){
            cString += cString
        }
        
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
        
        var r:CUnsignedInt = 0,g:CUnsignedInt = 0,b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        
        
        return UIColor(red: CGFloat(r) / 255.0,green: CGFloat(g) / 255.0,blue: CGFloat(b) / 255.0,alpha: CGFloat(1))
    }


func CGColorFromRGB(rgbValue: UInt) -> CGColor {
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,blue: CGFloat(rgbValue & 0x0000FF) / 255.0,alpha: CGFloat(1.0)
        ).cgColor
    }

猜你在找的Swift相关文章