UIColor is created using hex method (extension)

Every time you use UIColor, you have to convert back and forth, and the parameters given by the design are generally in hexadecimal. The conversion back and forth is troublesome, so write an extension to solve this problem.

The usage is roughly as follows:

NSColor.init(hex: "#333333")
NSColor.init(hex: "0x333333")
NSColor.init(hex: "333333")

The specific implementation of the extension is as follows:

import Foundation
import UIKit

extension UIColor {
    
    
    /// 使用 #FFFFFF 来初始化颜色
    convenience init(hex: String, alpha: CGFloat = 1.0) {
    
    
        var hexFormatted: String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

        if hexFormatted.hasPrefix("#") {
    
    
            hexFormatted = String(hexFormatted.dropFirst())
        }
        
        if hexFormatted.hasPrefix("0x") {
    
    
            hexFormatted = String(hexFormatted.dropFirst())
            hexFormatted = String(hexFormatted.dropFirst())
        }

        assert(hexFormatted.count == 6, "Invalid hex code used.")

        var rgbValue: UInt64 = 0
        Scanner(string: hexFormatted).scanHexInt64(&rgbValue)

        self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                  green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                  blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                  alpha: alpha)
    }
}

Guess you like

Origin blog.csdn.net/xo19882011/article/details/132312170