2017-10-16 332 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數組的內容已更改。