
import** Foundation
**class** DSGradientCircleView: UIView {
**private** **var** startColor: UIColor
**private** **var** endColor: UIColor
**private** **var** circleHeight: CGFloat
**init**(startColor: UIColor, endColor: UIColor, height: CGFloat) {
**self**.startColor = startColor
**self**.endColor = endColor
**self**.circleHeight = height
**super**.init(frame: .zero)
backgroundColor = .clear
}
**required** **init**?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
**override** **func** draw(_ rect: CGRect) {
**guard** **let** context = UIGraphicsGetCurrentContext() **else** { **return** }
**let** colors = [startColor.cgColor, endColor.cgColor]
**let** colorSpace = CGColorSpaceCreateDeviceRGB()
**let** colorLocations: [CGFloat] = [0.0, 1.0]
**guard** **let** gradient = CGGradient(colorsSpace: colorSpace, colors: colors **as** CFArray, locations: colorLocations) **else** { **return** }
**let** centerPoint = CGPoint(x: rect.midX, y: rect.midY)
**let** startRadius: CGFloat = 0
**let** endRadius = rect.width / 2
**let** path = UIBezierPath(arcCenter: centerPoint, radius: endRadius, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: **true**)
context.addPath(path.cgPath)
context.clip()
context.drawRadialGradient(gradient, startCenter: centerPoint, startRadius: startRadius, endCenter: centerPoint, endRadius: endRadius, options: .drawsBeforeStartLocation)
}
}
使用:
layoutSubviews()
addGradientCircle()
**private** **func** addGradientCircle() {
**let** gradientCircleView = DSGradientCircleView(startColor: UIColor.brand_30, endColor: UIColor.brand_0, height: DSDevice.screenWidth)
insertSubview(gradientCircleView, at: 0)
gradientCircleView.snp.makeConstraints {
$0.center.equalTo(**self**)
$0.width.height.equalTo(DSDevice.screenWidth)
}
}
```
- 效果
![image.png](https: