SwiftUI绘制路径和文本

时间:2020-10-20 11:02:37

标签: swiftui drawing

我正在移植旧的Objective C应用程序,在其中我使用属性字符串在-(void)drawRect:(CGRect)rect。中编写文本。

我无法使用SwiftUI路径绘制文本。我发现了一个类似的问题,没有任何答案(Mac OS X - SwiftUI - how to draw a String (text) together with some path

假设我需要在屏幕中间的水平线上写一个标签。

使用以下代码,该行显示在预期位置。文字不会显示。

struct TestView: View {
    var body: some View {
        GeometryReader { geometry in
            contentView(geometry: geometry)
        }
    }

    func contentView(geometry: GeometryProxy) -> some View {
        let content = VStack {
            ZStack {
                LineAndText()
                    .stroke()
            }
        }
        return content
    }
}

struct LineAndText: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: CGPoint(x: 0, y: rect.size.height / 2))
            path.addLine(to: CGPoint(x: rect.width, y: rect.size.height / 2))
            
            let label = "label"
            label.draw(at: CGPoint(x:0, y:rect.size.height / 2))
        }
    }
}

如何在所需位置书写文字?

注意:实际情况要复杂得多,我有很多行具有不同的垂直和水平标签,因此我需要在像素级别上控制标签位置。

0 个答案:

没有答案