美文网首页
Swift 16进制转颜色

Swift 16进制转颜色

作者: BankChang | 来源:发表于2016-11-30 10:48 被阅读0次

    extension UIColor{

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

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

    if cString.hasPrefix("#") {

    let index = cString.index(after: cString.startIndex)

    cString = cString.substring(from: index)

    }

    if cString.characters.count != 6 {

    return UIColor.black

    }

    let rRange = cString.startIndex ..< cString.index(cString.startIndex, offsetBy: 2)

    let rString = cString.substring(with: rRange)

    print(rString);

    let gRange = cString.index(cString.startIndex, offsetBy: 2) ..< cString.index(cString.startIndex, offsetBy: 4)

    let gString = cString.substring(with: gRange)

    print(gString);

    let bRange = cString.index(cString.startIndex, offsetBy: 4) ..< cString.index(cString.startIndex, offsetBy: 6)

    let bString = cString.substring(with: bRange)

    print(bString);

    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: alpha)

    }

    }

    相关文章

      网友评论

          本文标题:Swift 16进制转颜色

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