你如何从 CGColorSpace 获得 Unmanaged<CGColorSpace> ?

fye*_*ell 1 core-graphics ios swift vimage

我正在用 Swift 编写一个函数,它vImage_CGImageFormat从 a创建 aCGImage如下:

vImage_CGImageFormat(
    bitsPerComponent: UInt32(CGImageGetBitsPerComponent(image)), 
    bitsPerPixel: UInt32(CGImageGetBitsPerPixel(image)), 
    colorSpace: CGImageGetColorSpace(image), 
    bitmapInfo: CGImageGetBitmapInfo(image), 
    version: UInt32(0), 
    decode: CGImageGetDecode(image), 
    renderingIntent: CGImageGetRenderingIntent(image))
Run Code Online (Sandbox Code Playgroud)

然而,这不会编译。这是因为CGImageGetColorSpace(image)回报CGColorSpace!与上述构造只需要Unmanaged<CGColorSpace>colorSpace参数。

有没有另一种方法可以做到这一点?也许转换CGColorSpaceUnmanaged<CGColorSpace>?

Mar*_*n R 5

这应该有效:

vImage_CGImageFormat(
    // ...
    colorSpace: Unmanaged.passUnretained(CGImageGetColorSpace(image)),
    //...
)
Run Code Online (Sandbox Code Playgroud)

来自struct Unmanaged<T>API 文档:

/// Create an unmanaged reference without performing an unbalanced
/// retain.
///
/// This is useful when passing a reference to an API which Swift
/// does not know the ownership rules for, but you know that the
/// API expects you to pass the object at +0.
///
/// ::
///
///   CFArraySetValueAtIndex(.passUnretained(array), i,
///                          .passUnretained(object))
static func passUnretained(value: T) -> Unmanaged<T>
Run Code Online (Sandbox Code Playgroud)

Swift 3 更新:

vImage_CGImageFormat(
    // ...
    colorSpace: Unmanaged.passUnretained(image.colorSpace!),
    //...
)
Run Code Online (Sandbox Code Playgroud)