我正在尝试使用SwiftUI绘制以下形状:
在SwiftUI之前,我只需要创建一个UIBezierPath,使用addArc添加角点,然后最后调用close(),但是在SwiftUI路径上调用closeSubpath时,不会得到相同的结果。
这是我的代码:
Path { path in
let width: CGFloat = 23
let height: CGFloat = 24
let arrowWidth = height / 2.0
let cornerRadius = height / 7.5
path.addArc(center: CGPoint(x: width - cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: -90), endAngle: .zero, clockwise: true)
path.addLine(to: CGPoint(x: width, y: height - cornerRadius))
path.addArc(center: CGPoint(x: width - cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: .zero, endAngle: Angle(degrees: 90), clockwise: true)
path.addArc(center: CGPoint(x: arrowWidth + cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 135), clockwise: true)
path.addArc(center: CGPoint(x: cornerRadius, y: height / 2.0), radius: cornerRadius, startAngle: Angle(degrees: 135), endAngle: Angle(degrees: 225), clockwise: true)
path.addArc(center: CGPoint(x: arrowWidth + cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: 225), endAngle: Angle(degrees: -90), clockwise: true)
path.closeSubpath()
}
.foregroundColor(.red)
谢谢!
答案 0 :(得分:0)
应通过Shape
绘制,该路径指定rect为路径,如下面的演示中所示
注意:也固定为顺时针方向
struct NewShape_Previews: PreviewProvider {
static var previews: some View {
NewShape()
.frame(width: 100, height: 48)
.foregroundColor(Color.red)
}
}
struct NewShape: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
let width: CGFloat = rect.width
let height: CGFloat = rect.height
let arrowWidth = height / 2.0
let cornerRadius = height / 7.5
path.addArc(center: CGPoint(x: width - cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: -90), endAngle: .zero, clockwise: false)
path.addLine(to: CGPoint(x: width, y: height - cornerRadius))
path.addArc(center: CGPoint(x: width - cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: .zero, endAngle: Angle(degrees: 90), clockwise: false)
path.addArc(center: CGPoint(x: arrowWidth + cornerRadius, y: height - cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 135), clockwise: false)
path.addArc(center: CGPoint(x: cornerRadius, y: height / 2.0), radius: cornerRadius, startAngle: Angle(degrees: 135), endAngle: Angle(degrees: 225), clockwise: false)
path.addArc(center: CGPoint(x: arrowWidth + cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: Angle(degrees: 225), endAngle: Angle(degrees: -90), clockwise: false)
}
}
}