CGPathMoveToPoint在创建路径

时间:2016-09-05 09:06:29

标签: ios swift cgpath xcode8

我使用以下代码从CGPoint array()创建路径。

public func creatPath (for points:[CGPoint]) {
    let path = CGMutablePath()
    let startPoint = points.first

    CGPathMoveToPoint( path, CGAffineTransform.identity, startPoint.x, startPoint.y)

    var index = 0
    for point in points {
        if index == 0 { continue }
        CGPathAddLineToPoint(path, nil, points.x, points.y)
        index += 1
    }
    path.closeSubpath()
}

但它总是最终向我显示以下错误:

  

nil与预期的参数类型UnsafePointer <CGAffineTransForm>

不兼容

我也尝试过使用CGAffineTransform.identity然后显示:

  

无法转换类型&#39; CGAffineTransform&#39;的值预期参数类型&#39; UnsafePointer <CGAffineTransform>&#39;

我不确定我们还能在这里使用什么。我正在使用Xcode8 beta 6. Swift 3.0

编辑:当我尝试: -

var transform = CGAffineTransform.identity as CGAffineTransform;
CGPathMoveToPoint( path, &transform, startPoint.x, startPoint.y)

它显示:

  

&#39; CGPathMoveToPoint&#39;不可用:使用move(to:transform :)

尝试时:

CGPathMoveToPoint( path, NSNull(), startPoint.x, startPoint.y)
  

错误是:无法转换类型&#39; NSNull&#39;的值预期参数类型&#39; UnsafePointer&#39;

1 个答案:

答案 0 :(得分:3)

Swift 3为CGMutablePath提供了一个改进的,面向对象的界面。最重要的是: transform 参数有一个默认值,可以省略。

public func creatPath (for points:[CGPoint]) {
    let path = CGMutablePath()
    let startPoint = points.first

    path.move(to: startPoint)

    var index = 0
    for point in points {
        if index == 0 { continue }
        path.addLine(to: point)
        index += 1
    }
    path.closeSubpath()
}

注意:我已将循环变量从points更改为point,以避免与参数名称冲突。

<强>更新

您可以简化代码:

public func creatPath (for points:[CGPoint]) {
    let path = CGMutablePath()
    path.addLines(between: points)
    path.closeSubpath()
}