将 CGBitmapContextCreate 从 Objective-C 翻译成 Swift

Translate CGBitmapContextCreate from Objective-C to Swift

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。但是我不知道怎么办。

您可以使用本机 Swift 数组,然后调用其 withUnsafeMutableBytes 方法来获取数组存储的 UnsafeMutableRawBufferPointerbaseAddress 属性 然后将缓冲区的地址作为 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 returns 时发生了变化。