Swift 十六进制字符串转颜色

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

swift 3.0 语法有一定变化,相应字符串截取变化也不小,所以重写了一下取颜色的方法如下:

    func transferStringToColor(colorStr:String) -> UIColor {
        
        var color = UIColor.red
        var cStr : String = colorStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if cStr.hasPrefix("#") {
            let index = cStr.index(after: cStr.startIndex)
            cStr = cStr.substring(from: index)
        }
        if cStr.characters.count != 6 {
            return UIColor.black
        }
        //两种不同截取字符串的方法
        let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex,offsetBy: 2)
        let rStr = cStr.substring(with: rRange)
        
        let gRange = cStr.index(cStr.startIndex,offsetBy: 2) ..< cStr.index(cStr.startIndex,offsetBy: 4)
        let gStr = cStr.substring(with: gRange)
        
        let bIndex = cStr.index(cStr.endIndex,offsetBy: -2)
        let bStr = cStr.substring(from: bIndex)
        
        color = UIColor.init(colorLiteralRed: Float(changeToInt(numStr: rStr)) / 255,green: Float(changeToInt(numStr: gStr)) / 255,blue: Float(changeToInt(numStr: bStr)) / 255,alpha: 1)
        return color
    }
}

    func changeToInt(numStr:String) -> Int {
    
    let str = numStr.uppercased()
    var sum = 0
    for i in str.utf8 {
        //0-9 从48开始
        sum = sum * 16 + Int(i) - 48
        if i >= 65 {
            //A~Z 从65开始,但初始值为10
            sum -= 7
        }
    }
    return sum
}


当然,最好还是用Scanner来实现十六进制字符串转数字


 func transferStringToColor(_ colorStr:String) -> UIColor {
        
        var color = UIColor.red
        var cStr : String = colorStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if cStr.hasPrefix("#") {
            let index = cStr.index(after: cStr.startIndex)
            cStr = cStr.substring(from: index)
        }
        if cStr.characters.count != 6 {
            return UIColor.black
        }
        
        let rRange = cStr.startIndex ..< cStr.index(cStr.startIndex,offsetBy: -2)
        let bStr = cStr.substring(from: bIndex)
        
        var r:CUnsignedInt = 0,g:CUnsignedInt = 0,b:CUnsignedInt = 0;
        Scanner(string: rStr).scanHexInt32(&r)
        Scanner(string: gStr).scanHexInt32(&g)
        Scanner(string: bStr).scanHexInt32(&b)
        
        color = UIColor(red: CGFloat(r) / 255.0,green: CGFloat(g) / 255.0,blue: CGFloat(b) / 255.0,alpha: CGFloat(1))
        
        return color
    }
原文链接:https://www.f2er.com/swift/322929.html

猜你在找的Swift相关文章