在 SwiftUI 中在图像上绘制文本的矢量

问题描述 投票:0回答:1

我想绘制在图像中间有文本的向量,并且能够使文本保持在向量的中心

Example

有什么简单的方法可以用 SwiftUI 做到这一点吗?或者有类似的有用的库吗?

swift swiftui frontend measurement
1个回答
1
投票

您可以使用

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)
            }
    }
}

Vector

© www.soinside.com 2019 - 2024. All rights reserved.