利用 UIBezierPath 實現圓環進度條
Published in
4 min readNov 23, 2022
目的:練習function,action,outlet,UIBezierPath
import UIKit
class ViewController: UIViewController {
let aDegree = CGFloat.pi / 180 //宣告一度為何
let lineWidth: CGFloat = 10 //圓環框線的粗度
let radius: CGFloat = 100 //宣告半徑
let startDegree: CGFloat = 270 //宣告起始位置
@IBOutlet weak var percent: UILabel! //圓心Label
@IBOutlet weak var progressNum: UITextField! //宣告輸入的數字
@IBOutlet weak var circleView: UIView! //方便設置圓心
override func viewDidLoad() {
super.viewDidLoad()
backgroundCircle() //一開始先載入背景
}
//背景圓環
func backgroundCircle() {
let background = UIBezierPath(arcCenter: circleView.center, radius: radius, startAngle: aDegree*startDegree, endAngle: aDegree*(startDegree+360), clockwise: true)
let backgroundLayer = CAShapeLayer()
backgroundLayer.path = background.cgPath
backgroundLayer.fillColor = UIColor.clear.cgColor
backgroundLayer.lineWidth = lineWidth
backgroundLayer.strokeColor = UIColor.gray.cgColor
view.layer.addSublayer(backgroundLayer)
}
//進度條
func progressCircle(progress: Double) {
let progressPath = UIBezierPath(arcCenter: circleView.center, radius: radius, startAngle: aDegree*startDegree, endAngle: aDegree*(startDegree + 360 * progress / 100), clockwise: true)
let progressLayer = CAShapeLayer()
progressLayer.path = progressPath.cgPath
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineWidth = lineWidth
progressLayer.strokeColor = UIColor.systemTeal.cgColor
progressLayer.lineCap = .round //調整線條端點形狀.round代表圓型
view.layer.addSublayer(progressLayer)
}
//點擊Calculate
@IBAction func inputNumber(_ sender: Any) {
backgroundCircle() //重置
let number = Double(progressNum.text!) //將字串轉換成浮點數
progressCircle(progress: number!)
percent.text = progressNum.text! + "%"
}
}