## How to create a Path with a loop

 Jan '24 I'm trying to write some code to draw arithmatical functions, like sine(x), or log(x). The problem I encounter is that in order to draw it you have to iterate over a range of numbers, to create a Path. In the swiftUI environment ForEach cannot be used, because tou have to return a view after each iteration. A function, returning a Path-object doesn't do me any good, because it can apparently not been drawn, or is not accepted as a Path object. So I'm stuck. The only solution I can think of right now is to stick with do old way and not use SwiftUi for the UI. So the question is is there a way to draw something like this using SwiftUI. My code so far (simplified) is : A function returning a CGPoint : func SimpleLine(x: Double) -> CGPoint { var y: Double = log(x + 1) return CGPoint(x: x, y: y) A function creating a Path object : func fillPath() -> Path { var path: Path = Path() path.move(to: CGPoint(x: 20, y: 0)) for x in 0..<100 { let pnt: CGPoint = SimpleLine(x: Double(x)) print("(pnt)") path.addLine(to: pnt) } path.closeSubpath() return path } ``````And the only way I could imagine to implement it: var body: some View { NavigationView () { fillPath() .stroke(Color.green) } }`````` 2 Jan '24 Not sure what your `simpleLine` func draws, but you can implement your idea as follows: ``````struct MyShape: Shape { func path(in rect: CGRect) -> Path { var path = Path() path.move(to: CGPoint(x: 20, y: 0)) for x in 0..<100 { let point: CGPoint = simpleLine(x: Double(x)) path.addLine(to: point) } path.closeSubpath() return path } func simpleLine(x: Double) -> CGPoint { var y: Double = log(x + 1) return CGPoint(x: x, y: y) } }`````` and then you can use `MyShape` where you need. 2 Jan '24 Thank you @ygeras for you're answer. I am looking for ways to use graphical editting in my app. So had been looking for uses of Shape, but couldnt find any clues in the documentation about mouse interaction after drawing a Shape, so my idea was that I have more change of implementing mouse interaction using a 'plain' Path. It is clear however trahe there is no easy way of doing this. I'm quite new to this, so maybe this is a waste of everybody's time and is there a way to do this, hidden in the jungle of SwiftUi docs, somewhere. 2

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Sponsor Hacking with Swift and reach the world's largest Swift community!

### Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

You are not logged in