美文网首页
iOS - 16进制RGB转UIColor

iOS - 16进制RGB转UIColor

作者: love_ll | 来源:发表于2020-07-02 10:33 被阅读0次

  在程序开发中UI设计师给到颜色都是16进制的RGB数值或者RGBA数值。那就需要我们把16进制的RGB或者RGBA转成UIColor。

一、宏定义转换

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define UIColorFromRGBA(rgbaValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF000000) >> 24))/255.0 green:((float)((rgbValue & 0xFF0000) >> 16))/255.0 blue:((float)((rgbValue & 0xFF00) >> 8))/255.0 alpha:((float)(rgbValue & 0xFF))/255.0]

二、扩展UIColor转换

extension UIColor {
    
    static func colorWithRGB(_ rgb: String) -> UIColor {
        return UIColor.colorWithRGBA(rgb + "ff")
    }
    
    static func colorWithRGBA(_ rgba: String) -> UIColor {
        var hex: String = rgba.lowercased()
        if rgba.count < 6 {
            return UIColor.clear
        }
        if rgba.hasPrefix("0x"){
            hex = String(rgba[rgba.index(rgba.startIndex, offsetBy: 2)...])
        }
        if rgba.hasPrefix("#") {
            hex = String(rgba[rgba.index(rgba.startIndex, offsetBy: 1)...])
        }
        if hex.count != 8{
            return UIColor.clear
        }
        
        var startIndex = hex.index(hex.startIndex, offsetBy: 0)
        var endIndex = hex.index(startIndex, offsetBy: 2)
        var scanner = Scanner(string: String(hex[startIndex..<endIndex]))
        var r: UInt64 = 0
        scanner.scanHexInt64(&r)
        startIndex = hex.index(hex.startIndex, offsetBy: 2)
        endIndex = hex.index(startIndex, offsetBy: 2)
        scanner = Scanner(string: String(hex[startIndex..<endIndex]))
        var g: UInt64 = 0
        scanner.scanHexInt64(&g)
        startIndex = hex.index(hex.startIndex, offsetBy: 4)
        endIndex = hex.index(startIndex, offsetBy: 2)
        scanner = Scanner(string: String(hex[startIndex..<endIndex]))
        var b: UInt64 = 0
        scanner.scanHexInt64(&b)
        startIndex = hex.index(hex.startIndex, offsetBy: 6)
        endIndex = hex.index(startIndex, offsetBy: 2)
        scanner = Scanner(string: String(hex[startIndex..<endIndex]))
        var a: UInt64 = 0
        scanner.scanHexInt64(&a)
        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0)
    }
    
    static func colorWithRGB(_ rgb: Int64) -> UIColor {
        return UIColor.init(red: CGFloat(((rgb & 0xFF0000) >> 16))/255.0, green: CGFloat(((rgb & 0xFF00) >> 8))/255.0, blue: CGFloat((rgb & 0xFF))/255.0, alpha: 1.0)
    }
    
    static func colorWithRGBA(_ rgba: Int64) -> UIColor {
        return UIColor.init(red: CGFloat(((rgba & 0xFF000000) >> 24))/255.0, green: CGFloat(((rgba & 0xFF0000) >> 16))/255.0, blue: CGFloat(((rgba & 0xFF0000) >> 8))/255.0, alpha: CGFloat((rgba & 0xFF))/255.0)
    }

相关文章

网友评论

      本文标题:iOS - 16进制RGB转UIColor

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