IHRadialGradientLayer.swift 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // IHRadialGradientLayer.swift
  3. // Inhealth
  4. //
  5. // Created by weclouds on 2020/4/17.
  6. // Copyright © 2020 weclouds. All rights reserved.
  7. //
  8. import UIKit
  9. class IHRadialGradientLayer: CALayer {
  10. var center : CGPoint {
  11. return CGPoint(x: bounds.width / 2, y: bounds.height / 2)
  12. }
  13. var radius :CGFloat {
  14. return (bounds.width + bounds.height) / 2
  15. }
  16. var colors : [UIColor] = [UIColor.purple,UIColor.white]{
  17. didSet{
  18. setNeedsDisplay()
  19. }
  20. }
  21. var cgColors : [CGColor] {
  22. return colors.map { (color) -> CGColor in
  23. return color.cgColor
  24. }
  25. }
  26. override init() {
  27. super.init()
  28. needsDisplayOnBoundsChange = false
  29. }
  30. required init?(coder: NSCoder) {
  31. super.init()
  32. }
  33. override func draw(in ctx: CGContext) {
  34. ctx.saveGState()
  35. let colorSpace = CGColorSpaceCreateDeviceRGB()
  36. let locations :[CGFloat] = [0.0,1.0]
  37. let gradient = CGGradient(colorsSpace: colorSpace, colors: cgColors as CFArray, locations: locations)
  38. ctx.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
  39. }
  40. }