CAGradientLayer+Extension.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // CAGradientLayer+Extension.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by mac on 2024/4/11.
  6. //
  7. import UIKit
  8. public enum ViewGradientDirection {
  9. /// 水平从左到右
  10. case horizontal
  11. /// 垂直从上到下
  12. case vertical
  13. public func point() -> (CGPoint, CGPoint) {
  14. switch self {
  15. case .horizontal:
  16. return (CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0))
  17. case .vertical:
  18. return (CGPoint(x: 0, y: 0), CGPoint(x: 0, y: 1))
  19. }
  20. }
  21. }
  22. public extension CAGradientLayer {
  23. // MARK: 1.1、设置渐变色图层
  24. /// 设置渐变色图层
  25. /// - Parameters:
  26. /// - direction: 渐变方向
  27. /// - gradientColors: 渐变的颜色数组(颜色的数组)
  28. /// - gradientLocations: 设置渐变颜色的终止位置,这些值必须是递增的,数组的长度和 colors 的长度最好一致
  29. func gradientLayer(_ direction: ViewGradientDirection = .horizontal, _ gradientColors: [Any], _ gradientLocations: [NSNumber]? = nil, _ transform: CATransform3D? = nil) -> CAGradientLayer {
  30. // 设置渐变的颜色数组
  31. self.colors = gradientColors
  32. // 设置渐变颜色的终止位置,这些值必须是递增的,数组的长度和 colors 的长度最好一致
  33. self.locations = gradientLocations
  34. // 设置渲染的起始结束位置(渐变方向设置)
  35. self.startPoint = direction.point().0
  36. self.endPoint = direction.point().1
  37. if let weakTransform = transform {
  38. self.transform = weakTransform
  39. }
  40. return self
  41. }
  42. }