我应该使用 Swift ContiguousArray 来保存图像数据吗?
Should I be using Swift ContiguousArray's to hold image data?
我目前正在使用 [UInt8]
类型的缓冲区来保存从 CGImage 读取的像素数据,如下所示:
var pixels = [UInt8](repeatElement(0, count: bytesPerRow*Int(height)))
let context = CGContext.init(data: &pixels,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo)
context!.draw(cgImage, in: rect)
此代码一般假设 pixels
是一个包含图像数据的连续字节数组,它似乎工作正常。我有这种不安的感觉,我应该为此使用 ContiguousArray
。我在这里真的很危险,应该做点别的吗?
旁白:当我总是知道发生了什么时,我想念普通的 C。唉。
ContiguousArray
和 Array
之间的主要区别是后者在元素类型是 class 或 @objc
协议时使用不同的存储(就是这样可以很容易地连接到 Obj-C)。如果元素类型不是 class,它们都在内部使用相同的存储,您选择哪一种都没有关系。
在您的例子中,元素类型不是 class,因此 [UInt8]
的行为与 ContiguousArray<UInt8>
相同。
我目前正在使用 [UInt8]
类型的缓冲区来保存从 CGImage 读取的像素数据,如下所示:
var pixels = [UInt8](repeatElement(0, count: bytesPerRow*Int(height)))
let context = CGContext.init(data: &pixels,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo)
context!.draw(cgImage, in: rect)
此代码一般假设 pixels
是一个包含图像数据的连续字节数组,它似乎工作正常。我有这种不安的感觉,我应该为此使用 ContiguousArray
。我在这里真的很危险,应该做点别的吗?
旁白:当我总是知道发生了什么时,我想念普通的 C。唉。
ContiguousArray
和 Array
之间的主要区别是后者在元素类型是 class 或 @objc
协议时使用不同的存储(就是这样可以很容易地连接到 Obj-C)。如果元素类型不是 class,它们都在内部使用相同的存储,您选择哪一种都没有关系。
在您的例子中,元素类型不是 class,因此 [UInt8]
的行为与 ContiguousArray<UInt8>
相同。