Reputation: 3796
I have a function that receives a Data object together with a width and height. The data is a so called "normalised" image in binary form. Each pixel consists out of 3 Float values for the R, G, B colors ranging from 0 -> 1.0 (instead of the typical 0-255 for UInt8 values, but here we have floats). In fact its a sort of 2 dimensional array with a width and a height like this:
How can extract the R, G, B values as Swift floats from the Data object? This is what I came up with so far:
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 = ...
}
}
}
Upvotes: 2
Views: 1960
Reputation: 539975
You can use withUnsafeBytes()
to access the raw data as an array of Float
values:
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]
// ...
}
}
}
}
Upvotes: 3
Reputation: 124
var r= data[0];
var g = data[1];
var b = data[2];
element.background-color =rgba(r,g,b,1)
perhaps your looking for something like this?
Upvotes: -1