#23 利用 UIBezierPath 實現圓環進度條,甜甜圈圖表 & 圓餅圖

張又壬
4 min readJan 4, 2022

--

環形進度條

先畫底下灰色的圈圈

UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: radius*2, height: radius*2))

這邊給的點是左上角,再來畫上面的進度條

UIBezierPath(arcCenter: CGPoint(x: progressCenter.x, y: progressCenter.y), radius: radius, startAngle: aDegree * startDegree, endAngle: aDegree * (startDegree + 360 * percentage / 100), clockwise: true)

跟灰色圈圈不太一樣,給的點是中心點,我的 radius 是 50,lineWidth 是 10,畫在 100 X 100 的 UIView 的正中間,會看到圈圈超出 UIView 一點點,一開始還不知道為什麼會這樣,直到我又加了一個 110 X 110 的 UIView 壓在下面,這樣上下左右,剛好都會凸出來 5,這樣我畫出來的圈圈就剛剛好在第二個 UIView 裡面了,原來我畫出來的圈圈的寬度是內外各長一半的。

甜甜圈圖

畫法跟上面的進度條差不多,就是 lineWidth 粗一點,再來就是需要計算每一段的 endDegree,因為都跟上面的進度條畫法差不多,所以我又多加個動畫的練習,用 CABasicAnimation 把每段圖長出來,又因為要依序播出動畫,所以又練習了 CAAnimationDelegate,每完成一段動畫就會呼叫到 animationDidStop,然後再接下一段的動畫,直到全部畫完。

圓餅圖

圓餅圖的畫法跟上面兩個就有點不一樣了,上面畫的是線段,這邊畫的是一塊區域,所以要上色的話就不是對 strokeColor 上色了,而是對 fillColor 上色,而畫法就是要先 move 到圓的中心,在畫弧型,然後再 Close (可以省略),再來就跟畫甜甜圈圖的時候一樣,要計算每段圖的 enDegree

let percentagePath = UIBezierPath()
percentagePath.move(to: getPieChartViewCenter())
percentagePath.addArc(withCenter: getPieChartViewCenter(), radius: radius, startAngle: aDegree * startDegree, endAngle: aDegree * endDegree, clockwise: true)
percentagePath.close()

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

張又壬
張又壬

Written by 張又壬

目前正在努力學習 swift

No responses yet

Write a response