Swift 16進符号化変換UICOLOR

2750 ワード

あまり話さないで、直接コードをつけてください.

import UIKit

// MARK:  16 UIColor
extension UIColor {
    
    convenience init?(hexNum: Int) {
        self.init(hexStr: String(hexNum, radix: 16))
    }
    
    convenience init?(hexStr: String) {
        var hex = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        if hex.hasPrefix("#") {
            hex.remove(at: hex.startIndex)
        }
        if hex.hasPrefix("0x") || hex.hasPrefix(("0X")) {
            hex.removeSubrange((hex.startIndex ..< hex.index(hex.startIndex, offsetBy: 2)))
        }
        
        guard let hexNum = Int(hex, radix: 16) else {
            self.init()
            return nil
        }
        switch hex.characters.count {
        case 3:
            self.init(red: CGFloat(((hexNum & 0xF00) >> 8).duplicate4bits) / 255.0,
                      green: CGFloat(((hexNum & 0x0F0) >> 4).duplicate4bits) / 255.0,
                      blue: CGFloat((hexNum & 0x00F).duplicate4bits) / 255.0,
                      alpha: 1.0)
        case 4:
            self.init(red: CGFloat(((hexNum & 0xF000) >> 12).duplicate4bits) / 255.0,
                      green: CGFloat(((hexNum & 0x0F00) >> 8).duplicate4bits) / 255.0,
                      blue: CGFloat(((hexNum & 0x00F0) >> 4).duplicate4bits) / 255.0,
                      alpha: CGFloat((hexNum & 0x000F).duplicate4bits) / 255.0)
        case 6:
            self.init(red: CGFloat((hexNum & 0xFF0000) >> 16) / 255.0,
                      green: CGFloat((hexNum & 0x00FF00) >> 8) / 255.0,
                      blue: CGFloat((hexNum & 0x0000FF) >> 0) / 255.0,
                      alpha: 1.0)
        case 8:
            self.init(red: CGFloat((hexNum & 0xFF000000) >> 24) / 255.0,
                      green: CGFloat((hexNum & 0x00FF0000) >> 16) / 255.0,
                      blue: CGFloat((hexNum & 0x0000FF00) >> 8) / 255.0,
                      alpha: CGFloat(hexNum & 0x000000FF) / 255.0)
        default:
            self.init()
            return nil
        }
    }
    
}

private extension Int {
    var duplicate4bits: Int {
        return self << 4 + self
    }
}


**使用法:**
let colorR = UIColor(hexStr: "0xf00f")
let colorG = UIColor(hexStr: "0X0f0f")
let colorB = UIColor(hexStr: "#0fff")

let colorRR = UIColor(hexStr: "0xff0000ff")
let colorGG = UIColor(hexStr: "0X00ff00ff")
let colorBB = UIColor(hexStr: "#0000ffff")

let colorRN = UIColor(hexNum: 0xf00f)
let colorGN = UIColor(hexNum: 0x00ff00)
let colorBN = UIColor(hexNum: 0x0000ff)