Trying to access the pixel data on a Canvas
, and almost there I think? But I have missed some detail? This compiles but the cgContext.data
doesn't seem to be set to a value I can extract here?
The line variable refers to a published array of points.
class Lines:ObservableObject {
@Published var coordinates:[CGPoint] = []
}
struct ContentView: View {
@ObservedObject var line = Lines()
@GestureState var foo = CGPoint.zero
var body: some View {
ZStack(alignment: .center) {
Color.yellow
.opacity(0.1)
Canvas { context, size in
context.withCGContext { cgContext in
cgContext.setStrokeColor(UIColor.red.cgColor)
cgContext.setLineWidth(12)
if line.coordinates.count > 2 {
cgContext.move(to: line.coordinates[0])
for p in 1..<line.coordinates.count {
cgContext.move(to: line.coordinates[p - 1])
cgContext.addLine(to: line.coordinates[p])
cgContext.drawPath(using: .eoFillStroke)
}
if cgContext.data != nil {
let rawData:UnsafeMutableRawPointer = cgContext.data!
let opaquePtr = OpaquePointer(rawData)
let contextPtr = UnsafeMutablePointer<UInt32>(opaquePtr)
let pixels = UnsafeMutableBufferPointer<UInt32>(start: contextPtr, count: 256 * 256)
print("pixels ",pixels.count)
}
}
}
}
}
}