我有一个接收数据对象以及宽度和高度的函数。数据是二进制形式的所谓“规范化”图像。 每个像素由3种R,G,B颜色的Float值组成,范围从0-> 1.0(而不是UInt8值的典型0-255,但是这里有float)。实际上,它是一种二维数组,其宽度和高度如下:
当Swift从Data对象浮动时,如何提取R,G,B值?到目前为止,这是我想出的:
func convert(data: Data, width: Int, height: Int) {
let sizeFloat = MemoryLayout.size(ofValue: CGFloat.self)
for x in 0...width {
for y in 0...height {
let index = ( x + (y * width) ) * sizeFloat * 3
let dataIndex = Data.Index(???)
data.copyBytes(to: <#T##UnsafeMutableBufferPointer<DestinationType>#>??, from: <#T##Range<Data.Index>?#>???)
let Red = ....
let Green = ...
let Blue = ...
}
}
}
答案 0 :(得分:3)
您可以使用withUnsafeBytes()
以Float
值数组的形式访问原始数据:
func convert(data: Data, width: Int, height: Int) {
data.withUnsafeBytes { (floatPtr: UnsafePointer<Float>) in
for x in 0..<width {
for y in 0..<height {
let index = (x + y * width) * 3
let red = floatPtr[index]
let green = floatPtr[index+1]
let blue = floatPtr[index+2]
// ...
}
}
}
}
答案 1 :(得分:0)
var r= data[0];
var g = data[1];
var b = data[2];
element.background-color =rgba(r,g,b,1)
也许您正在寻找这样的东西?