[英]Custom RoundedRectangle Shape
要繪制帶有圓角的自定義形狀, .addArc
是你的朋友。
struct LabelShape: Shape {
let cornerRadius: CGFloat
let tabWidth: CGFloat
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: cornerRadius, y: rect.height))
path.addArc(tangent1End: CGPoint(x: rect.width, y: rect.height), tangent2End: CGPoint(x: rect.width, y: 0), radius: cornerRadius)
path.addArc(tangent1End: CGPoint(x: rect.width, y: 0), tangent2End: CGPoint(x: 0, y: 0), radius: cornerRadius)
path.addArc(tangent1End: CGPoint(x: rect.width - tabWidth, y: 0), tangent2End: CGPoint(x: rect.width - tabWidth, y: rect.height), radius: cornerRadius)
path.addArc(tangent1End: CGPoint(x: rect.width - tabWidth, y: cornerRadius * 2), tangent2End: CGPoint(x: 0, y: cornerRadius * 2), radius: cornerRadius)
path.addArc(tangent1End: CGPoint(x: 0, y: cornerRadius * 2), tangent2End: CGPoint(x: 0, y: rect.height), radius: cornerRadius)
path.addArc(tangent1End: CGPoint(x: 0, y: rect.height), tangent2End: CGPoint(x: rect.width, y: rect.height), radius: cornerRadius)
return path
}
}
你可以這樣使用:
struct ContentView: View {
var body: some View {
ZStack(alignment: .topTrailing) {
LabelShape(cornerRadius: 10, tabWidth: 110)
.stroke(.red)
.frame(width: 300, height: 100)
HStack(alignment: .firstTextBaseline, spacing: 4) {
Text("01:59:43")
.font(.system(size: 14, weight: .bold))
Text("Hours")
.font(.system(size: 10, weight: .regular))
}
.padding(4)
}
}
}
有關此版本的addArc
工作原理的詳細解釋,請參閱https://stackoverflow.com/a/71683201/123632
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.