// // MP_CircularProgressView.swift // MusicPlayer // // Created by 忆海16 on 2024/5/14. // import Foundation import UIKit class CircularProgressView: UIView { private var progressLayer = CAShapeLayer() private var trackLayer = CAShapeLayer() public var progress: CGFloat = 0 { didSet { progressLayer.strokeEnd = progress } } override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupView() } // private func setupLayers() { // // Track layer (background circle) // let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) // let circularPath = UIBezierPath(arcCenter: center, radius: bounds.width / 2, startAngle: -CGFloat.pi / 2, endAngle: 3 * CGFloat.pi / 2, clockwise: true) // // trackLayer.path = circularPath.cgPath // trackLayer.strokeColor = UIColor.lightGray.cgColor // trackLayer.lineWidth = 3 // trackLayer.fillColor = UIColor.clear.cgColor // layer.addSublayer(trackLayer) // // // Progress layer (foreground circle) // progressLayer.path = circularPath.cgPath // progressLayer.strokeColor = UIColor.green.cgColor // progressLayer.lineWidth = 3 // progressLayer.fillColor = UIColor.clear.cgColor // progressLayer.lineCap = .round // progressLayer.strokeEnd = 0 // layer.addSublayer(progressLayer) // } // // func setProgress(to progress: CGFloat) { // self.progress = progress // } private func setupView() { // 设置轨道图层 trackLayer.path = createCircularPath().cgPath trackLayer.fillColor = UIColor.clear.cgColor trackLayer.strokeColor = UIColor.lightGray.cgColor trackLayer.lineWidth = 3 trackLayer.strokeEnd = 1.0 layer.addSublayer(trackLayer) // 设置进度图层 progressLayer.path = createCircularPath().cgPath progressLayer.fillColor = UIColor.clear.cgColor progressLayer.strokeColor = UIColor.green.cgColor progressLayer.lineWidth = 3 progressLayer.strokeEnd = 0.0 layer.addSublayer(progressLayer) } private func createCircularPath() -> UIBezierPath { return UIBezierPath(arcCenter: center, radius: bounds.size.width / 2, startAngle: -.pi / 2, endAngle: .pi * 3 / 2, clockwise: true) } func setProgress(to progress: CGFloat) { self.progress = progress print("Updating progress to: \(progress)") DispatchQueue.main.async { self.progressLayer.strokeEnd = progress } } }