swiftUI使用16进制颜色值
2021-01-20 11:37:14

swiftUI的默认Color类没有提供使用16进制颜色的方法,我们可以通过扩展Color类使用hex色值。

import Foundation
import SwiftUI

extension Color {
    init(hex: Int, alpha: Double = 1) {
        let components = (
            R: Double((hex >> 16) & 0xff) / 255,
            G: Double((hex >> 08) & 0xff) / 255,
            B: Double((hex >> 00) & 0xff) / 255
        )
        self.init(
            .sRGB,
            red: components.R,
            green: components.G,
            blue: components.B,
            opacity: alpha
        )
    }
  
    static func hex(hex: Int, alpha: Double = 1) -> Color {
        return Color.init(hex: hex, alpha: alpha)
    }
}

每日一句
Waste no more time arguing what a good man should be, be one. - Marcus Aurelius