Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free hand drawing on image in SwiftUI [closed]

I wanted to draw lines on the image. https://stackoverflow.com/a/60002068/12759144 link helps to draw on the shapes. I set gesture to image and tried drawing lines on the image. but it is not drawing the lines on the image.

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)

Attached screen for reference. enter image description here

like image 330
cto platform Avatar asked Jan 26 '26 04:01

cto platform


1 Answers

Here is fast implementation of drawing on Rectangle, but you can put any view you need. I used Path and saved every point at the DragGesture and than use these points to draw 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
    }
}

with code above you can achieve this:

enter image description here

like image 85
Hrabovskyi Oleksandr Avatar answered Jan 28 '26 04:01

Hrabovskyi Oleksandr