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

o7jaxewo  于 2023-09-30  发布在  Swift
关注(0)|答案(1)|浏览(95)

我想画矢量有一个在图像中间的文本,并能够保持在矢量文本居中

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

qxsslcnc

qxsslcnc1#

您可以使用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)
            }
    }
}

相关问题