// // UIColor+Ex.swift // KittensTravelNotes // // Created by 100Years on 2025/7/6. // import SwiftUI public extension UIColor { /// 返回一个随机颜色 static var random: UIColor { return UIColor( red: CGFloat.random(in: 0...1), green: CGFloat.random(in: 0...1), blue: CGFloat.random(in: 0...1), alpha: 1.0 ) } static func fromHex(_ hex: String, alpha: CGFloat = 1.0) -> UIColor { var cleanedHex = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() // Remove leading "#" if present if cleanedHex.hasPrefix("#") { cleanedHex.removeFirst() } // Ensure valid hex length guard cleanedHex.count == 6 else { return UIColor.clear // Return clear color for invalid input } // Extract RGB components var rgbValue: UInt64 = 0 Scanner(string: cleanedHex).scanHexInt64(&rgbValue) let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0 let blue = CGFloat(rgbValue & 0x0000FF) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: alpha) } var color: Color { return Color(self) } }