GradientView.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // GradientView.swift
  3. // Runner
  4. //
  5. // Created by liukai on 2024/7/4.
  6. //
  7. import UIKit
  8. class GradientView: UIView {
  9. override func draw(_ rect: CGRect) {
  10. guard let context = UIGraphicsGetCurrentContext() else { return }
  11. let colors = [UIColor(hex: "#091D44").cgColor, UIColor(hex: "#245A8A").cgColor, UIColor(hex: "#7F7CEC").cgColor]
  12. let colorSpace = CGColorSpaceCreateDeviceRGB()
  13. let colorLocations: [CGFloat] = [0.0, 0.5, 1.0]
  14. guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocations) else { return }
  15. let startPoint = CGPoint.zero
  16. let endPoint = CGPoint(x: 0, y: bounds.height)
  17. context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])
  18. }
  19. }
  20. extension UIColor {
  21. convenience init(hex: String) {
  22. var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
  23. hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
  24. var rgb: UInt64 = 0
  25. Scanner(string: hexSanitized).scanHexInt64(&rgb)
  26. let red = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
  27. let green = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
  28. let blue = CGFloat(rgb & 0x0000FF) / 255.0
  29. self.init(red: red, green: green, blue: blue, alpha: 1.0)
  30. }
  31. }