SwiftUI工具(二)—— SwiftUI扩展Color增加hex、rgb方法实现快速自定义颜色

//
//  MyColors.swift
//  SwiftUIStudy
//
//  Created by 李棒棒 on 2023/12/19.
//

import Foundation
import SwiftUI

extension Color {
    
    /// 字符串 16进制转化颜色
    /// - Parameter hex: 例如 "0xffffff" "#ffffff" "ffffff"
    /// - Parameter alpha: 透明度 0~1
    /// - Returns: Color
    init(_ hex: String, alpha: Double = 1.0) {
        var hex = hex
        hex = hex.trimmingCharacters(in: .whitespaces)
        
        if hex.hasPrefix("#") {
            hex = (hex as NSString).replacingOccurrences(of: "#", with: "")
        }else if hex.hasPrefix("0x") {
            hex = (hex as NSString).replacingOccurrences(of: "0x", with: "")
        }
        
        if hex.count != 6 {
            self = Color.clear
        }
        
        var rgbValue: UInt64 = 0
        if Scanner(string: hex).scanHexInt64(&rgbValue) {
            let components = (
                R: Double((rgbValue >> 16) & 0xff) / 255.0,
                G: Double((rgbValue >> 08) & 0xff) / 255.0,
                B: Double((rgbValue >> 00) & 0xff) / 255.0
            )
            self = Color(.sRGB, red: components.R, green: components.G, blue: components.B, opacity: alpha)
        }else {
            self = Color.clear
        }
    }
    
    ///  16进制转化颜色
    /// - Parameters:
    /// - Parameter   hex: 例如 0xffffff
    /// - Parameter   alpha: 透明度 0~1
    /// - Returns: Color
    init(_ hex: Int, a: Double = 1.0){
        let components = (
            R:  Double((hex >> 16) & 0xff) / 255.0,
            G:  Double((hex >> 08) & 0xff) / 255.0,
            B:  Double((hex >> 00) & 0xff) / 255.0
        )
       self = Color(.sRGB, red: components.R, green: components.G, blue: components.B, opacity: a)
    }
    
    /// 0~255 转化颜色
    /// - Parameter colorSpace: 颜色域,默认 Color.RGBColorSpace
    /// - Parameter r: red 0~255
    /// - Parameter g: green 0~255
    /// - Parameter b: blue 0~255
    /// - Parameter a: 透明度 0~1.0
    /// - Returns: Color
    init(_ colorSpace: Color.RGBColorSpace = .sRGB,
                    r: Int,
                    g: Int,
                    b: Int,
                    a: Double = 1.0){
        
      self = Color(colorSpace, red: Double(r) / 255.0,
                    green: Double(g) / 255.0,
                    blue: Double(b) / 255.0,
                    opacity: a)
    }
    
}
BangBang

欢迎大家交流学习,点点关注开发不迷路

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容