2017-10-16 167 views
-4
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。但是我不知道怎么做。将CGBitmapContextCreate从Objective-C翻译成Swift

+0

请参阅[__Apple Docs__](https://developer.apple.com/documentation/swift/unsafemutablerawpointer)以获取更多信息,也许? – holex

回答

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数组的内容已更改。