Search code examples
positionswiftuicgpoint

CPoint positioning SwiftUI


I am drawing a line with Path, and on that line I want to have a circle if I play around I can get the circle on the line of course. However I do not understand why this code does not put the circle on the line:

struct CircleOnLineView: View {
    func createCirle() -> some View {
        return Circle().fill(Color.blue)
    }

    var body: some View {
        GeometryReader { geometry in
            ZStack {

                Path { path in
                    path.move(to: CGPoint(x: 0, y: geometry.size.height / 2))
                    path.addLine(to: CGPoint(x: geometry.size.width, y: geometry.size.height / 2))
                    }
                .stroke(Color.gray, lineWidth: 3)
                Circle()
                    .fill(Color.blue)
                    .position(CGPoint(x: 0 , y: geometry.size.height / 2))
                .frame(width: 5, height: 5)

            }
        }

    }
}

Result of positioning


Solution

  • Order of modifiers in this case is important. Here is how it is expected (1st - made size of shape, 2nd - position it):

    enter image description here

    Circle()
        .fill(Color.blue)
        .frame(width: 5, height: 5)
        .position(CGPoint(x: 0 , y: geometry.size.height / 2))