Home > database >  Why does my path show me a triangle instead of a hexagon?
Why does my path show me a triangle instead of a hexagon?

Time:09-27

I've tried to create two kinds of hexagons with paths. The first hexagon displays the output I expected, but the second one only shows me a triangle. What is happening here and how would you fix it?

The working one:

struct Hexagon: View {
    
    var sideLength: CGFloat = 0.2
    var sideLength2: CGFloat {
        1 - sideLength
    }
    
    var body: some View {
        Path { path in
            let width: CGFloat = 200
            let height: CGFloat = 200
            
            path.move(to: CGPoint(x: width * sideLength, y: height * 0))
            path.addLine(to: CGPoint(x: width * 0, y: height * 0.5 ))
            path.addLine(to: CGPoint(x: width * sideLength, y: height * 1))
            path.addLine(to: CGPoint(x: width * sideLength2, y: height * 1))
            path.addLine(to: CGPoint(x: width * 1, y: height * 0.5 ))
            path.addLine(to: CGPoint(x: width * sideLength2, y: height * 0))
            
            path.closeSubpath()
        }
        .stroke(Color.green, lineWidth: 10)
    }
} 

The not working one (well it compiles, but it doesn't show a hexagon):

struct Hexagon2: View {
    var sideLength: CGFloat = 0.2
    var sideLength2: CGFloat {
        1 - sideLength
    }
    
    var body: some View {
        Path { path in
            let width: CGFloat = 200
            let height: CGFloat = 200
            
            path.move(to: CGPoint(x: width * 0.5, y: height * 0))
            path.addLine(to: CGPoint(x: width * 0, y: sideLength))
            path.addLine(to: CGPoint(x: width * 0, y: sideLength2))
            path.addLine(to: CGPoint(x: width * 0.5, y: height * 1))
            path.addLine(to: CGPoint(x: width * 1, y: sideLength2))
            path.addLine(to: CGPoint(x: width * 1, y: sideLength))
            
            path.closeSubpath()
        }
        .stroke(Color.blue, lineWidth: 10)
    }
}

CodePudding user response:

Your sideLength and sideLength2 are merely scaling factors. You need to multiply them by width or height to get the final value:

        path.move(to: CGPoint(x: width * 0.5, y: height * 0))
        path.addLine(to: CGPoint(x: width * 0, y: height * sideLength))
        path.addLine(to: CGPoint(x: width * 0, y: height * sideLength2))
        path.addLine(to: CGPoint(x: width * 0.5, y: height * 1))
        path.addLine(to: CGPoint(x: width * 1, y: height * sideLength2))
        path.addLine(to: CGPoint(x: width * 1, y: height * sideLength))
  • Related