我想绘制在图像中间有文本的向量,并且能够使文本保持在向量的中心
有什么简单的方法可以用 SwiftUI 做到这一点吗?或者有类似的有用的库吗?
您可以使用
Shape
构建向量,然后将其显示在 Text
标签后面。像这样的东西:
struct Vector: Shape {
let arrowWidth = CGFloat(15)
let arrowHeight = CGFloat(12)
let lineWidth = CGFloat(2)
func path(in rect: CGRect) -> Path {
var path = Path()
// The line at the top
path.move(to: CGPoint(x: rect.midX - (arrowWidth / 2), y: rect.minY + (lineWidth / 2)))
path.addLine(to: CGPoint(x: rect.midX + (arrowWidth / 2) , y: rect.minY + (lineWidth / 2)))
// The arrow at the top
path.move(to: CGPoint(x: rect.midX, y: rect.minY + lineWidth))
path.addLine(to: CGPoint(x: rect.midX + (arrowWidth / 2), y: rect.minY + arrowHeight))
path.addLine(to: CGPoint(x: rect.midX - (arrowWidth / 2), y: rect.minY + arrowHeight))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY + lineWidth))
path.closeSubpath()
// The central line
path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY - lineWidth))
// The arrow at the bottom
path.move(to: CGPoint(x: rect.midX, y: rect.maxY - lineWidth))
path.addLine(to: CGPoint(x: rect.midX + (arrowWidth / 2), y: rect.maxY - arrowHeight))
path.addLine(to: CGPoint(x: rect.midX - (arrowWidth / 2), y: rect.maxY - arrowHeight))
path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY - lineWidth))
path.closeSubpath()
// The line at the bottom
path.move(to: CGPoint(x: rect.midX - (arrowWidth / 2), y: rect.maxY - (lineWidth / 2)))
path.addLine(to: CGPoint(x: rect.midX + (arrowWidth / 2), y: rect.maxY - (lineWidth / 2)))
return path
}
}
struct ContentView: View {
var body: some View {
Color.yellow
.frame(width: 300, height: 300)
.overlay(alignment: .leading) {
Text("400mm ± 5")
.padding(.vertical, 4)
.background(Color.yellow)
.frame(maxHeight: .infinity)
.background {
Vector()
.stroke(lineWidth: 2)
.overlay(
Vector().fill()
)
}
.padding(.leading, 10)
}
}
}