UIColor+Ex.swift 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // UIColor+Ex.swift
  3. // KittensTravelNotes
  4. //
  5. // Created by 100Years on 2025/7/6.
  6. //
  7. import SwiftUI
  8. public extension UIColor {
  9. /// 返回一个随机颜色
  10. static var random: UIColor {
  11. return UIColor(
  12. red: CGFloat.random(in: 0...1),
  13. green: CGFloat.random(in: 0...1),
  14. blue: CGFloat.random(in: 0...1),
  15. alpha: 1.0
  16. )
  17. }
  18. static func fromHex(_ hex: String, alpha: CGFloat = 1.0) -> UIColor {
  19. var cleanedHex = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
  20. // Remove leading "#" if present
  21. if cleanedHex.hasPrefix("#") {
  22. cleanedHex.removeFirst()
  23. }
  24. // Ensure valid hex length
  25. guard cleanedHex.count == 6 else {
  26. return UIColor.clear // Return clear color for invalid input
  27. }
  28. // Extract RGB components
  29. var rgbValue: UInt64 = 0
  30. Scanner(string: cleanedHex).scanHexInt64(&rgbValue)
  31. let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
  32. let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
  33. let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
  34. return UIColor(red: red, green: green, blue: blue, alpha: alpha)
  35. }
  36. var color: Color {
  37. return Color(self)
  38. }
  39. }