来自 CGAffineTransform 的 UnsafePointer<CGAffineTransform>

UnsafePointer<CGAffineTransform> from CGAffineTransform

我正在尝试在 Swift 中创建 CGPath。我正在使用 CGPathCreateWithRect(rect, transformPointer).

如何从 CGAffineTransform 中获取 UnsafePointer<CGAffineTransform>?我试过这个:

    let transform : CGAffineTransform = CGAffineTransformIdentity
    let transformPointer : UnsafePointer<CGAffineTransform> = UnsafePointer(transform)

我也试过这个:

    let transform : CGAffineTransform = CGAffineTransformIdentity
    let transformPointer : UnsafePointer<CGAffineTransform> = &transform 

但是 Swift 抱怨 '&' with non-inout argument of type...。我也试过将 &transform 直接传递给 CGPathCreateWithRect 但由于同样的错误而停止。

当我直接传入transform时,Swift "Cannot convert value of type 'CGAffineTransform' to expected argument type 'UnsafePointer'".

这是怎么回事,如何使它与 Swift 2.1 一起工作?

I've also tried passing &transform directly into CGPathCreateWithRect ...

你快到了。 transform 需要是一个 变量 为了将它作为 inout 参数传递给 &:

var transform = CGAffineTransformIdentity
let path = CGPathCreateWithRect(CGRect(...), &transform)

有关详细信息,请参阅 "Interacting with C APIs" 在 "Using Swift with Cocoa and Objective-C" 文档中。


Swift 3 这将是

var transform = CGAffineTransform.identity
let path = CGPath(rect: rect, transform: &transform)

或者,对于恒等变换,只需

let path = CGPath(rect: rect, transform: nil)

@Martin R 提供了最佳答案,但作为替代方案,我喜欢以这种方式使用我的不安全可变指针,以防您将来需要更改实际指针

let path = withUnsafeMutablePointer(&transform)
{
  CGPathCreateWithRect(CGRect(...), UnsafeMutablePointer([=10=]))
}