swift 十六进制UIColor

class func colorWithHexString(hex: String) ->UIColor {

        var cString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {

            cString = cString.substring(from: 1)

        }

        if (cString.count != 6){

            return UIColor.red

        }

        let rString = cString.substring(to:2)

        let otherString = cString.substring(from:2)

        let gString = otherString.substring(to:2)

        let bString = otherString.substring(from: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))

    }


你可能感兴趣的:(Swift)