保存 PencilKit 图像 – SwiftUI

Saving PencilKit image – SwiftUI

我有一个 SwiftUI 视图,可以使用 UIViewRepresentable PencilKit 视图捕获用户签名。视图可以很好地捕获签名,但是当我尝试保存签名时,保存的文件是 blank/empty PNG 文件。

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) {

    }

}

你能试试这个吗:

if let img = drawImage(image), let data = img.pngData() { 
....
}

func drawImage(_ image: UIImage) -> UIImage? {
    guard let cgimg = image.cgImage else { return nil }
    UIGraphicsBeginImageContext(CGSize(width: cgimg.width, height: cgimg.height))
    image.draw(in: CGRect(x: 0, y: 0, width: cgimg.width, height: cgimg.height))
    let theimg = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return theimg
}

我认为你在这里使用了两种不同的 canvas。

尝试这样的事情:

struct PencilKitRepresentable : UIViewRepresentable {
    let canvas = PKCanvasView(frame: .init(x: 0, y: 0, width: 400, height: 80))
    func makeUIView(context: Context) -> PKCanvasView {
        return canvas
    }
    func updateUIView(_ uiView: PKCanvasView, context: Context) { }
}

和:

struct SignatureUI: View {
    let canvasView = PencilKitRepresentable()
    let imgRect = CGRect(x: 0, y: 0, width: 400.0, height: 100.0)

    var body: some View {
      VStack {
          Text ("Sign here:")
          canvasView.frame(height: 100.0)
              .border(Color.gray, width: 5)
          Button(action: {
              self.saveSignature()
          }) {
              Text("Save Signature")
          }
      }
  }

func saveSignature() {
    let image = canvasView.canvas.drawing.image(from: imgRect, scale: 1.0)
    ...

    }

}