如何从CGColorSpace获得Unmanaged <cgcolorspace>?</cgcolorspace>

时间:2015-02-06 08:29:43

标签: ios swift core-graphics vimage

我在Swift中编写一个函数,从vImage_CGImageFormat创建一个CGImage,如下所示:

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

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

还有其他办法吗?也许将CGColorSpace转换为Unmanaged<CGColorSpace>

1 个答案:

答案 0 :(得分:3)

这应该有效:

vImage_CGImageFormat(
    // ...
    colorSpace: Unmanaged.passUnretained(CGImageGetColorSpace(image)),
    //...
)

来自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>

Swift 3的更新:

vImage_CGImageFormat(
    // ...
    colorSpace: Unmanaged.passUnretained(image.colorSpace!),
    //...
)