ios – SwiftUI PencilKit Not Updating in Actual-Time When Picture is Behind Canvas


I’m engaged on a SwiftUI + PencilKit integration, and I’ve encountered an odd subject. After I place my PKCanvasView inside a ZStack with out a picture, every part works effective—the drawing updates in real-time as anticipated. Nevertheless, once I add a picture behind the canvas, real-time updates cease working. As an alternative:

  • Whereas drawing, the earlier strokes disappear, and the canvas appears empty.
  • As soon as I end dragging, the strokes reappear.
  • This habits doesn’t occur when there isn’t any picture behind the canvas.

My Code

import SwiftUI
import PencilKit

struct DrawingView2: UIViewRepresentable {
    @Binding var canvasView: PKCanvasView
    let toolPicker = PKToolPicker()

    func makeUIView(context: Context) -> PKCanvasView {
        canvasView.backgroundColor = .clear
        canvasView.isOpaque = false
        canvasView.isMultipleTouchEnabled = true
        canvasView.allowsFingerDrawing = true
        canvasView.drawingPolicy = .anyInput  // Permits real-time updates

        toolPicker.setVisible(true, forFirstResponder: canvasView)
        toolPicker.addObserver(canvasView)
        canvasView.becomeFirstResponder()

        return canvasView
    }

    func updateUIView(_ uiView: PKCanvasView, context: Context) {
        DispatchQueue.foremost.async {
            uiView.setNeedsDisplay()  // Forces view to refresh
        }
    }
}

ContentView with an Picture Behind the Canvas

struct ContentView2: View {
    @State personal var canvasView = PKCanvasView()

    var physique: some View {
        ZStack {
            Picture("img2")  // Background picture

            DrawingView2(canvasView: $canvasView)
                .body(maxWidth: .infinity, maxHeight: .infinity)
                .zIndex(11111)  // Excessive zIndex to make sure visibility
        }
        .edgesIgnoringSafeArea(.all)
    }
}

What I Tried
Setting isOpaque = false → No impact.
Calling setNeedsDisplay() in updateUIView → No impact.
Utilizing .zIndex(1) for the picture → No impact.
Setting allowsFingerDrawing = true → No impact.

enter image description here

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles