2016-09-05 84 views
1

我使用以下代碼從CGPoint array()創建路徑時遇到了一些問題。CGPathMoveToPoint在創建路徑

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 is not compatible with expected argument type UnsafePointer <CGAffineTransForm>

我一直在使用CGAffineTransform.identity也嘗試過那麼就說明:

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

我不知道我們可以用別的什麼這裏。我使用的測試Xcode8 6雨燕3.0

編輯:當我嘗試: -

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

它顯示:

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

雖然嘗試:

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

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

+1

這是因爲在Objective-C,我們這樣做:'CGAffineTransform變換= CGAffineTransformIdentity; CGPathAddLineToPoint(path,&transform,point.x,point.y);'帶「&var」的東西。如果你想通過'NULL',顯然你可以這樣做:http://stackoverflow.com/a/27169902/1801544(我不說Swift,我只是指出可能的解決方案/提示)。 – Larme

回答

3

Swift 3爲CGMutablePath提供了一個大大改進的,面向對象的接口。最棒的是:轉換參數有一個默認值,可以省略。

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

注:我已經改變了循環變量從pointspoint以避免與參數名稱衝突。

更新

您可以簡化代碼:

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

這太好了。非常感謝你的幫助!我在哪裏可以獲得Swift3的文檔?正如https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CGPath/#//apple_ref/c/func/CGPathCreateMutable仍然適用於Swift2.x,我想。 – rptwsthi

+0

我也對文檔感到困惑,因爲那裏有新舊文檔。看看[CGMutablePath - Core Graphics](https://developer.apple.com/reference/coregraphics/cgmutablepath)。它涵蓋了Swift 3的語法,但幾乎沒有任何描述。 – Codo