alionthego
alionthego

Reputation: 9703

How can I smooth out the curves of a drawn Path using SwiftUI with a fat Stroke?

I am making a basic drawing app and using the following tutorial to allow the user to draw:

https://martinmitrevski.com/2019/07/20/developing-drawing-app-with-swiftui/

The drawings are made using a DragGesture and then seaming together all the points observed in the onChange

GeometryReader { geometry in
    Path { path in
        for drawing in self.drawings {
            self.add(drawing: drawing, toPath: &path)
        }
        self.add(drawing: self.currentDrawing, toPath: &path)
    }
    .stroke(Color.black, lineWidth: 15.0)
    .background(Color(white: 0.95))
    .gesture(
        DragGesture(minimumDistance: 0.1)
            .onChanged({ (value) in
                let currentPoint = value.location
                if currentPoint.y >= 0
                    && currentPoint.y < geometry.size.height {
                    self.currentDrawing.points.append(currentPoint)
                }
                
            })
            .onEnded({ (value) in
                self.drawings.append(self.currentDrawing)
                self.currentDrawing = Drawing()
            })
    )
}
.frame(maxHeight: .infinity)



private func add(drawing: Drawing, toPath path: inout Path) {
        let points = drawing.points
        if points.count > 1 {
            for i in 0..<points.count-1 {
                let current = points[i]
                let next = points[i+1]
                path.move(to: current)
                path.addLine(to: next)
            }
        }
    }

The issue I'm having is that for fatter strokes the curves are badly broken up as shown below.

enter image description here

Is there anyway to smoothen out these curves using this approach?

Upvotes: 1

Views: 846

Answers (1)

DonMag
DonMag

Reputation: 77433

You're currently creating a new line segment for every point.

What you likely want to do is move To: the first point, and then addLine: To the successive points:

private func add(drawing: Drawing, toPath path: inout Path) {
    let points = drawing.points
    if points.count > 1 {
        path.move(to: points[0])
        for i in 1..<points.count-1 {
            path.addLine(to: points[i])
        }
    }
}

Upvotes: 2

Related Questions