네이티브 스위프트 배열을 사용하고 withUnsafeMutableBytes
메서드를 호출하여 UnsafeMutableRawBufferPointer
을 배열의 저장소로 가져올 수 있습니다. 그러면 baseAddress
속성은 버퍼의 주소를 UnsafeMutableRawPointer?
으로 가져옵니다. 포인터가 당신이 withUnsafeMutableBytes
에 전달 폐쇄 내부에서만 유효 함을
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
배열의 내용이 변경되었습니다.
자세한 정보는 [__Apple Docs__] (https://developer.apple.com/documentation/swift/unsafemutablerawpointer)를 참조하십시오. – holex