多步生成贝塞尔正方形

Generating a Bezier Square in Multiple Steps

我可以用这个标准代码生成一个正方形。

func drawSquare() {
    let width:CGFloat = 100
    var square = UIBezierPath()
    square.moveToPoint(CGPoint(x: 0, y: 0))
    square.addLineToPoint(CGPoint(x: width, y: 0))
    square.addLineToPoint(CGPoint(x: width, y: width))
    square.addLineToPoint(CGPoint(x: 0, y: width))
    square.lineWidth = 5
    square.closePath()
    UIColor.blackColor().setStroke()
    square.stroke()
}

但是,如果我想分两步绘制每个 addLineToPoint() 线段,我的正方形将不再正确绘制。

func drawSquare2Steps() {
    let width:CGFloat = 200
    let mult:CGFloat = 2
    var square = UIBezierPath()
    square.moveToPoint(CGPoint(x: 0, y: 0))

    square.addLineToPoint(CGPoint(x: 100, y: 0)) // 1
    square.addLineToPoint(CGPoint(x: 200, y: 0)) // 2
    square.addLineToPoint(CGPoint(x: 200, y: 100)) // 3
    square.addLineToPoint(CGPoint(x: 200, y: 200)) // 4
    square.addLineToPoint(CGPoint(x: 100, y: 200)) // 5
    square.addLineToPoint(CGPoint(x: 0, y: 200)) //6

    square.lineWidth = 5
    square.closePath() // 7
    UIColor.orangeColor().setStroke()
    square.stroke()
}

这是我看到的路径:

我试图在这张图片中描述这个功能:

我的最终目标不是画正方形,而是更复杂的路径。正方形简单地说明了我复杂路径的问题。

除了您的视图大小是 (100, 100) 但正方形大小是 (200,200),所以您看不到整个正方形,没有什么问题。