美文网首页
十六进制转颜色

十六进制转颜色

作者: 陌上北辰 | 来源:发表于2016-12-18 00:10 被阅读13次

    在 开发的过程中UID 给我们的高保真图颜色大多会是十六进制,我们在项目中需要转换:

    
    import UIKit
    
    
    func HEXCOLOR(_ string: String) -> UIColor {
        if string.characters.count == 6 {
            var red: CUnsignedInt? = 0, green: CUnsignedInt? = 0, blue: CUnsignedInt? = 0
            
            let range1 = string.startIndex..<string.characters.index(string.startIndex, offsetBy: 2)
            let range2 = string.characters.index(string.startIndex, offsetBy: 2)..<string.characters.index(string.startIndex, offsetBy: 4)
            let range3 = string.characters.index(string.startIndex, offsetBy: 4)..<string.characters.index(string.startIndex, offsetBy: 6)
            
            let _ = (Scanner.localizedScanner(with: string.substring(with: range1)) as AnyObject).scanHexInt32(&red!)
            let _ = (Scanner.localizedScanner(with: string.substring(with: range2)) as AnyObject).scanHexInt32(&green!)
            let _ = (Scanner.localizedScanner(with: string.substring(with: range3)) as AnyObject).scanHexInt32(&blue!)
            
            return RGB(CGFloat(red!), CGFloat(green!), CGFloat(blue!))
        }
        return UIColor.clear
    }
    

    相关文章

      网友评论

          本文标题:十六进制转颜色

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