Color+Ex.swift 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // Color+Ex.swift
  3. // TSLiveWallpaper
  4. //
  5. // Created by 100Years on 2025/1/14.
  6. //
  7. import SwiftUI
  8. public extension Color {
  9. public static func hex(_ hex: String) -> Color {
  10. let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
  11. var int: UInt64 = 0
  12. Scanner(string: hex).scanHexInt64(&int)
  13. let a, r, g, b: UInt64
  14. switch hex.count {
  15. case 3: // RGB (12-bit)
  16. (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
  17. case 6: // RGB (24-bit)
  18. (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
  19. case 8: // ARGB (32-bit)
  20. (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
  21. default:
  22. (a, r, g, b) = (255, 0, 0, 0)
  23. }
  24. return Self(
  25. .sRGB,
  26. red: Double(r) / 255,
  27. green: Double(g) / 255,
  28. blue: Double(b) / 255,
  29. opacity: Double(a) / 255
  30. )
  31. }
  32. // 随机生成一个颜色
  33. public static var randomColor: Color {
  34. // 随机生成 R, G, B 和 alpha(透明度)值
  35. let red = Double.random(in: 0 ... 1)
  36. let green = Double.random(in: 0 ... 1)
  37. let blue = Double.random(in: 0 ... 1)
  38. let alpha = Double.random(in: 0.5 ... 1) // 可选,透明度的范围
  39. return Color(red: red, green: green, blue: blue, opacity: alpha)
  40. }
  41. }