rptwsthi rptwsthi - 3 months ago 256
iOS Question

CGPathMoveToPoint have some trouble in creating path

I a using following code to create path from

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()
}


But it always end up showing me following error:


nil is not compatible with expected argument type UnsafePointer
<CGAffineTransForm>



I have also tried using
CGAffineTransform.identity
Then it shows:


Cannot convert value of type 'CGAffineTransform' to expected argument type 'UnsafePointer
<CGAffineTransform>
'


I am not sure what else can we use here. I am using Xcode8 beta 6. Swift 3.0

Edit: When I try:-

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


It shows:


'CGPathMoveToPoint' is unavailable: Use move(to:transform:)


And while trying:

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



Error is: Cannot convert value of type 'NSNull' to expected argument type 'UnsafePointer'

Answer

Swift 3 has a much improved, object-oriented interface for CGMutablePath. Best of all: the transform parameter has a default value and can be omitted.

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()
}

Note: I've changed the loop variable from points to point to avoid to collision with the parameter name.

Update

You can simplify your code:

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