直接上代码:
class CircularProgressBarView: UIView {
private let backgroundLayer = CAShapeLayer()
private let progressLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
private func configure() {
// 创建底部圆形路径
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let lineWidth: CGFloat = 3 // 圆环路径宽度
let radius = (min(bounds.width, bounds.height) - lineWidth) / 2 // 圆的半径
let startAngle = -CGFloat.pi / 2 // 起始角度
let endAngle = 1.5 * CGFloat.pi // 终点角度
let backgroundPath = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
// 配置底部CAShapeLayer
backgroundLayer.path = backgroundPath.cgPath
backgroundLayer.strokeColor = UIColor.white.withAlphaComponent(0.4).cgColor // 底部圆的颜色
backgroundLayer.fillColor = UIColor.clear.cgColor
backgroundLayer.lineWidth = lineWidth // 进度条宽度
backgroundLayer.lineCap = .round
layer.addSublayer(backgroundLayer)
// 创建进度条圆形路径
let progressPath = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
// 配置进度条CAShapeLayer
progressLayer.path = progressPath.cgPath
progressLayer.strokeColor = UIColor(hex: 0x00BF60).cgColor // 进度条颜色
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineWidth = lineWidth // 进度条宽度
progressLayer.lineCap = .round
// 设置初始进度
progressLayer.strokeEnd = 0
layer.addSublayer(progressLayer)
}
func setProgress(_ progress: Float, animated: Bool) {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = progressLayer.strokeEnd
animation.toValue = progress
animation.duration = animated ? 1.0 : 0
progressLayer.strokeEnd = CGFloat(progress)
progressLayer.add(animation, forKey: "progressAnimation")
}
}