GradientButton.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // UIView+Gradient.swift
  3. // Bark
  4. //
  5. // Created by huangfeng on 2023/2/10.
  6. // Copyright © 2023 Fin. All rights reserved.
  7. //
  8. import UIKit
  9. typealias GradientPoints = (startPoint: CGPoint, endPoint: CGPoint)
  10. enum GradientOrientation {
  11. case topRightBottomLeft
  12. case topLeftBottomRight
  13. case horizontal
  14. case vertical
  15. var startPoint: CGPoint {
  16. return points.startPoint
  17. }
  18. var endPoint: CGPoint {
  19. return points.endPoint
  20. }
  21. var points: GradientPoints {
  22. switch self {
  23. case .topRightBottomLeft:
  24. return (CGPoint(x: 0.0, y: 1.0), CGPoint(x: 1.0, y: 0.0))
  25. case .topLeftBottomRight:
  26. return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1, y: 1))
  27. case .horizontal:
  28. return (CGPoint(x: 0.0, y: 0.5), CGPoint(x: 1.0, y: 0.5))
  29. case .vertical:
  30. return (CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.0, y: 1.0))
  31. }
  32. }
  33. }
  34. class GradientButton: UIButton {
  35. lazy var gradient: CAGradientLayer = {
  36. let gradient = CAGradientLayer()
  37. return gradient
  38. }()
  39. func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) {
  40. gradient.frame = self.bounds
  41. gradient.colors = colours.map { $0.cgColor }
  42. gradient.startPoint = orientation.startPoint
  43. gradient.endPoint = orientation.endPoint
  44. if gradient.superlayer == nil {
  45. self.layer.insertSublayer(gradient, at: 0)
  46. }
  47. }
  48. override func layoutSubviews() {
  49. super.layoutSubviews()
  50. gradient.frame = self.bounds
  51. }
  52. }