Newer
Older
Productization_H5_IOS / template / Common / Tool / UIColor+Ex.swift
@zhangfeng zhangfeng on 8 Aug 2023 2 KB commit first

import Foundation
import UIKit

extension UIColor {
    /// rgb
    public static func rgb(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1.0) -> UIColor {
        return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
    }

    /// 16进制颜色
    public static func hex(_ hex: Int, a: CGFloat = 1.0) -> (UIColor) {
        return UIColor(red: (CGFloat)((hex & 0xFF0000) >> 16) / 255.0, green: (CGFloat)((hex & 0xFF00) >> 8) / 255.0, blue: (CGFloat)(hex & 0xFF) / 255.0, alpha: a)
    }

//    /// 十六进制颜色字符串转UIColor
//    /// - Parameters:
//    ///   - hex: 支持0x 或者 # 或 直接6位长度的颜色字符串
//    ///   - alpha: 透明度 默认值 1
//    /// - Returns: description
//    public static func hexColor(_ hex: String, alpha: CGFloat = 1) -> UIColor {
//        var cStr = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
//
//        // 长度小于6 格式不对, 直接返回透明色
//        if cStr.count < 6 { return .clear }
//
//        if cStr.hasPrefix("0X") {
//            cStr = cStr.subStr(start: 2, length: 6)
//        } else if cStr.hasPrefix("#") {
//            cStr = cStr.subStr(start: 1, length: 6)
//        }
//
//        if cStr.count != 6 { return .clear }
//
//        var rgbValue: UInt64 = 0
//        Scanner(string: cStr).scanHexInt64(&rgbValue)
//
//        return UIColor(
//            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
//            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
//            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
//            alpha: alpha
//        )
//    }

    // https://blog.csdn.net/nb_tpl/article/details/43230085
    // 混合颜色,ratio 0~1
    public static func mixColor(color1: UIColor, color2: UIColor, radio: CGFloat) -> UIColor? {
        var ratio = radio
        if ratio > 1 {
            ratio = 1
        }
        guard let components1 = color1.cgColor.components else { return nil }
        guard let components2 = color2.cgColor.components else { return nil }
        let r = components1[0] * ratio + components2[0] * (1 - ratio)
        let g = components1[1] * ratio + components2[1] * (1 - ratio)
        let b = components1[2] * ratio + components2[2] * (1 - ratio)
        return UIColor(red: r, green: g, blue: b, alpha: 1)
    }
}