SwiftUI:绘制中间和边缘有曲线的形状
SwiftUI: drawing a shape with curves in the middle and edges
我正在努力在 SwiftUI 中绘制以下形状:
我可以这样画半个圆:
Circle()
.trim(from: 0.05, to: 0.45)
.frame(width: 75, height: 75)
.foregroundColor(.gray)
但我仍然不知道如何用圆角粘合这个圆来创建最终形状。
我需要使用具有这种形状的 HStack
。
自定义形状似乎最适合这里。有了它你可以使用 .clipShape
修饰符来实现你想要的:
struct MyShape: Shape{
func path(in rect: CGRect) -> Path {
let width = rect.size.width
let height = rect.size.height
let circleWidth = width * 0.2
let point1 = CGPoint(x: 0, y: height)
let point2 = CGPoint(x: 0, y: height * 0.2)
let point3 = CGPoint(x: width * 0.4, y: 0)
let point4 = CGPoint(x: width * 0.8, y: 0)
let point5 = CGPoint(x: width, y: height)
return Path{ path in
path.move(to: point1)
path.addLine(to: point2)
path.addArc(center: .init(x: width * 0.1, y: width * 0.1), radius: width * 0.1, startAngle: .init(degrees: 180), endAngle: .init(degrees: 270), clockwise: false)
path.addLine(to: point3)
path.addArc(center: .init(x: width / 2, y: 0), radius: circleWidth / 2, startAngle: .init(degrees: 180), endAngle: .init(degrees: 0), clockwise: true)
path.addLine(to: point4)
path.addArc(center: .init(x: width * 0.9, y: width * 0.1), radius: width * 0.1, startAngle: .init(degrees: 270), endAngle: .init(degrees: 0), clockwise: false)
path.addLine(to: point5)
path.closeSubpath()
}
}
}
示例:
HStack{
Rectangle()
}
.clipShape(MyShape())
输出:
我正在努力在 SwiftUI 中绘制以下形状:
我可以这样画半个圆:
Circle()
.trim(from: 0.05, to: 0.45)
.frame(width: 75, height: 75)
.foregroundColor(.gray)
但我仍然不知道如何用圆角粘合这个圆来创建最终形状。
我需要使用具有这种形状的 HStack
。
自定义形状似乎最适合这里。有了它你可以使用 .clipShape
修饰符来实现你想要的:
struct MyShape: Shape{
func path(in rect: CGRect) -> Path {
let width = rect.size.width
let height = rect.size.height
let circleWidth = width * 0.2
let point1 = CGPoint(x: 0, y: height)
let point2 = CGPoint(x: 0, y: height * 0.2)
let point3 = CGPoint(x: width * 0.4, y: 0)
let point4 = CGPoint(x: width * 0.8, y: 0)
let point5 = CGPoint(x: width, y: height)
return Path{ path in
path.move(to: point1)
path.addLine(to: point2)
path.addArc(center: .init(x: width * 0.1, y: width * 0.1), radius: width * 0.1, startAngle: .init(degrees: 180), endAngle: .init(degrees: 270), clockwise: false)
path.addLine(to: point3)
path.addArc(center: .init(x: width / 2, y: 0), radius: circleWidth / 2, startAngle: .init(degrees: 180), endAngle: .init(degrees: 0), clockwise: true)
path.addLine(to: point4)
path.addArc(center: .init(x: width * 0.9, y: width * 0.1), radius: width * 0.1, startAngle: .init(degrees: 270), endAngle: .init(degrees: 0), clockwise: false)
path.addLine(to: point5)
path.closeSubpath()
}
}
}
示例:
HStack{
Rectangle()
}
.clipShape(MyShape())
输出: