iOS 径向渐变,圆形光圈

232 阅读1分钟

image.png

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://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/2b80f2e93d974778b85de36a4276571f~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgdXNlcjI5OTYzOTYxMjYyODY=:q75.awebp?rk3s=f64ab15b&x-expires=1773285368&x-signature=wVev8R5s2rpFz%2BegL4i0j%2Bh2rks%3D)