UIView+Theme.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // UIView+Theme.swift
  3. // Gami
  4. //
  5. // Created by OneeChan on 2026/4/1.
  6. //
  7. import Foundation
  8. import UIKit
  9. import Combine
  10. enum LNViewGradientDirection {
  11. case horizontalLTR
  12. case horizontalRTL
  13. case verticalUTD
  14. case verticalDTU
  15. case custom(start: CGPoint, endPoint: CGPoint)
  16. }
  17. extension UIView {
  18. static func gradientView(_ colors: [UIColor], _ direction: LNViewGradientDirection) -> UIView {
  19. let view = UIView()
  20. view.isUserInteractionEnabled = false
  21. let gradientLayer = CAGradientLayer()
  22. gradientLayer.colors = colors.map({ $0.cgColor })
  23. switch direction {
  24. case .horizontalLTR:
  25. gradientLayer.startPoint = .zero
  26. gradientLayer.endPoint = .init(x: 1, y: 0)
  27. case .horizontalRTL:
  28. gradientLayer.startPoint = .init(x: 1, y: 0)
  29. gradientLayer.endPoint = .zero
  30. case .verticalUTD:
  31. gradientLayer.startPoint = .zero
  32. gradientLayer.endPoint = .init(x: 0, y: 1)
  33. case .verticalDTU:
  34. gradientLayer.startPoint = .init(x: 0, y: 1)
  35. gradientLayer.endPoint = .zero
  36. case .custom(let start, let endPoint):
  37. gradientLayer.startPoint = start
  38. gradientLayer.endPoint = endPoint
  39. }
  40. view.layer.addSublayer(gradientLayer)
  41. view.publisher(for: \.bounds).removeDuplicates().sink
  42. { [weak gradientLayer] newValue in
  43. guard let gradientLayer else { return }
  44. gradientLayer.frame = newValue
  45. }.store(in: &view.cancellables)
  46. return view
  47. }
  48. }