将CGBitmapContextCreate从Objective-C翻译为Swift

时间:2017-10-16 13:22:54

标签: objective-c swift core-graphics swift4

unsigned char pixelData[4] = { 0, 0, 0, 0 };
CGContextRef context = CGBitmapContextCreate(pixelData,
    1,
    1,
    bitsPerComponent,
    bytesPerRow,
    colorSpace,
    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

我想将unsigned char pixelData[4] = { 0, 0, 0, 0 };翻译成Swift。我似乎必须使用UnsafeMutableRawPointer。但我不知道如何。

1 个答案:

答案 0 :(得分:0)

您可以使用本机Swift数组,然后调用其withUnsafeMutableBytes方法获取数组存储的UnsafeMutableRawBufferPointer。然后,baseAddress属性会将缓冲区的地址作为UnsafeMutableRawPointer?

以下是一个例子:

import CoreGraphics

var pixelData: [UInt8] = [0, 0, 0, 0]
pixelData.withUnsafeMutableBytes { pointer in
    guard let colorSpace = CGColorSpace(name: CGColorSpace.displayP3),
        let context = CGContext(data: pointer.baseAddress,
                                width: 1,
                                height: 1,
                                bitsPerComponent: 8,
                                bytesPerRow: 4,
                                space: colorSpace,
                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
    else {
        return
    }
    // Draw a white background
    context.setFillColor(CGColor.white)
    context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
}

print(pixelData) // prints [255, 255, 255, 255]

请注意,指针仅在传递给withUnsafeMutableBytes的闭包内有效。由于图形上下文假定此指针在上下文的生命周期内有效,因此从闭包返回上下文并从外部访问它将是未定义的行为。

然而,正如您所看到的,pixelData数组的内容在withUnsafeMutableBytes返回时已更改。