I have a SwiftUI view to capture a user signature using a UIViewRepresentable PencilKit view. The view is capturing the signature just fine, but when I try to save the signature, the file saved is a blank/empty PNG file.
import PencilKit
struct SignatureUI: View {
let canvasView = PKCanvasView(frame: .init(x: 0, y: 0, width: 400.0, height: 100.0))
let imgRect = CGRect(x: 0, y: 0, width: 400.0, height: 100.0)
let today = Date()
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}
var body: some View {
VStack {
Text ("Sign here:")
PencilKitRepresentable()
.frame(height: 100.0)
.border(Color.gray, width: 5)
Button(action: {
self.saveSignature()
}) {
Text("Save Signature")
}
}
}
func saveSignature() {
let image = canvasView.drawing.image(from: imgRect, scale: 1.0)
if let data = image.pngData() {
let filename = getDocumentsDirectory().appendingPathComponent("\(self.dateFormatter.string(from: self.today)).png")
try? data.write(to: filename)
print(filename)
}
}
}
struct PencilKitRepresentable : UIViewRepresentable {
func makeUIView(context: Context) -> PKCanvasView {
return PKCanvasView(frame: .init(x: 0, y: 0, width: 400, height: 80));
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
}
}