如何在SwiftUI中绘制箭头 附现有未完成实现代码
SwiftUI 箭头绘制实现方案
你当前代码的核心问题如下:
- 仅绘制了箭头尖端的两个斜边,缺少箭杆主体绘制逻辑
- 使用负y坐标,绘制内容会超出Path的frame可见范围,无法正常展示
- 声明的
change状态变量未被使用,动画没有触发源
以下是修改后的可运行实现,支持点击触发箭头翻转动画:
struct ContentView: View { @State private var change = false private let arrowWidth: CGFloat = 128 // 可自定义参数:箭头整体高度、尖端高度 private let arrowHeight: CGFloat = 150 private let arrowTipHeight: CGFloat = 30 var body: some View { Path { path in // 绘制箭杆:从底部中心向上延伸到箭尖底部 path.move(to: CGPoint(x: arrowWidth/2, y: arrowHeight)) path.addLine(to: CGPoint(x: arrowWidth/2, y: arrowTipHeight)) // 绘制箭尖左斜边 path.move(to: CGPoint(x: arrowWidth/2, y: 0)) path.addLine(to: CGPoint(x: 0, y: arrowTipHeight)) // 绘制箭尖右斜边 path.move(to: CGPoint(x: arrowWidth/2, y: 0)) path.addLine(to: CGPoint(x: arrowWidth, y: arrowTipHeight)) } .stroke(style: StrokeStyle(lineWidth: 3, lineCap: .round, lineJoin: .round)) .frame(width: arrowWidth, height: arrowHeight) .foregroundColor(.green) // 绑定状态触发旋转动画 .rotationEffect(.degrees(change ? 180 : 0)) .animation(.default, value: change) .onTapGesture { change.toggle() } .padding(.top, 100) } }
你可以通过修改参数快速调整箭头样式:
- 调整
arrowWidth修改箭头整体宽度 - 调整
arrowHeight修改箭头整体长度 - 调整
arrowTipHeight修改箭头尖端的倾斜角度 - 修改
StrokeStyle的lineWidth参数调整线条粗细 - 如果需要实心箭头,将
stroke修饰符替换为fill即可
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

