在 SwiftUI 中自由手绘图像

cto*_*orm 2 core-graphics swift ios13 swiftui

我想在图像上画线。/sf/answers/4200144791/链接有助于绘制形状。我将手势设置为图像并尝试在图像上绘制线条。但它没有在图像上绘制线条。

Image(uiImage: self.shareImage).renderingMode(.original).resizable().padding(5).gesture(DragGesture().onChanged( { value in self.addNewPoint(value))

                            })
                                .onEnded( { value in
                                    self.isFirstTouchBegan = false
                                }))

                            DrawShape(pointss: points)
                                .stroke(lineWidth: 5) 
                                .foregroundColor(.blue)
Run Code Online (Sandbox Code Playgroud)

附上画面供参考。 在此处输入图片说明

Але*_*кий 7

这是绘图的快速实现Rectangle,但您可以放置​​所需的任何视图。我使用Path并保存了每个点,DragGesture然后使用这些点来绘制Shape:

struct DrawExample: View {

    @State var points: [CGPoint] = []

    var body: some View {

        ZStack {
            Rectangle() // replace it with what you need
                .foregroundColor(.red)
                .edgesIgnoringSafeArea(.all)
                .gesture(DragGesture().onChanged( { value in
                    self.addNewPoint(value)
                })
                .onEnded( { value in
                    // here you perform what you need at the end
                }))


            DrawShape(points: points)
                .stroke(lineWidth: 5) // here you put width of lines
                .foregroundColor(.blue)
        }

    }

    private func addNewPoint(_ value: DragGesture.Value) {
        // here you can make some calculations based on previous points
        points.append(value.location)
    }

}

struct DrawShape: Shape {

    var points: [CGPoint]

    // drawing is happening here
    func path(in rect: CGRect) -> Path {
        var path = Path()
        guard let firstPoint = points.first else { return path }

        path.move(to: firstPoint)
        for pointIndex in 1..<points.count {
            path.addLine(to: points[pointIndex])

        }
        return path
    }
}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,您可以实现:

在此处输入图片说明