在前一天,我們畫出了針的雛型,而我想做的時鐘,是有時、分、秒針的。
時分秒的差別,我這邊選擇使用 enum。在 getLengthRatio() 上設定每根針的比例,在 getSpacing() 設定每根針的寬度。
enum HandLength {
case second
case minute
case hour
func getLengthRatio() -> Double {
switch self {
case .second:
return 1
case .minute:
return 0.9
case .hour:
return 0.7
}
}
func getSpacing() -> CGFloat {
switch self {
case .second:
return 2
case .minute:
return 4
case .hour:
return 6
}
}
}
struct HandShape: Shape {
var spacing: CGFloat {
return handLength.getSpacing()
}
var handLength: HandLength
func path(in rect: CGRect) -> Path {
var p = Path()
p.move(to: CGPoint(x: rect.midX - spacing, y: rect.midY))
p.addLine(to: CGPoint(x: rect.midX, y: getHandPointY(rect: rect, handLength: handLength)))
p.addLine(to: CGPoint(x: rect.midX + spacing, y: rect.midY))
return p
}
func getHandPointY(rect: CGRect, handLength: HandLength) -> CGFloat {
let edge = min(rect.size.width, rect.size.height)
return edge * ( 1 - handLength.getLengthRatio())
}
}
struct HandShape_Previews: PreviewProvider {
static var previews: some View {
Group {
HandShape(handLength: .second)
.fill(BCColor.secondHandColor)
.frame(width: 200, height: 200, alignment: .center)
.background(.cyan)
HandShape(handLength: .minute)
.fill(BCColor.minuteHandColor)
.frame(width: 200, height: 200, alignment: .center)
.background(.cyan)
HandShape(handLength: .hour)
.fill(BCColor.hourHandColor)
.frame(width: 200, height: 200, alignment: .center)
.background(.cyan)
}
.previewLayout(.sizeThatFits)
}
}
可以在下方看到三根針的 preview,嗯,這樣有符合三個長短不一樣的針的需求了。下一篇「錶盤」