I added a canvas view using PDFPageOverlayViewProvider. When I zoom the PDFView, the drawing is scaled, but its quality becomes blurry. How can I fix this?
import SwiftUI
import PDFKit
import PencilKit
import CoreGraphics
struct ContentView: View {
var body: some View {
if
let url = Bundle.main.url(forResource: "sample", withExtension: "pdf"),
let data = try? Data(contentsOf: url),
let document = PDFDocument(data: data)
{
PDFRepresentableView(document: document)
} else {
Text("fail")
}
}
}
#Preview {
ContentView()
}
struct PDFRepresentableView: UIViewRepresentable {
let document: PDFDocument
let pdfView = PDFView()
func makeUIView(context: Context) -> PDFView {
pdfView.displayMode = .singlePageContinuous
pdfView.usePageViewController(false)
pdfView.displayDirection = .vertical
pdfView.pageOverlayViewProvider = context.coordinator
pdfView.document = document
pdfView.autoScales = false
pdfView.minScaleFactor = 0.7
pdfView.maxScaleFactor = 4
return pdfView
}
func updateUIView(_ uiView: PDFView, context: Context) {
// Optional: update logic if needed
}
func makeCoordinator() -> CustomCoordinator {
return CustomCoordinator(parent: self)
}
}
class CustomCoordinator: NSObject, PDFPageOverlayViewProvider, PKCanvasViewDelegate {
let parent: PDFRepresentableView
init(parent: PDFRepresentableView) {
self.parent = parent
}
func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
let result = UIView()
let canvasView = PKCanvasView()
canvasView.drawingPolicy = .anyInput
canvasView.tool = PKInkingTool(.pen, color: .blue, width: 20)
canvasView.translatesAutoresizingMaskIntoConstraints = false
result.addSubview(canvasView)
NSLayoutConstraint.activate([
canvasView.leadingAnchor.constraint(equalTo: result.leadingAnchor),
canvasView.trailingAnchor.constraint(equalTo: result.trailingAnchor),
canvasView.topAnchor.constraint(equalTo: result.topAnchor),
canvasView.bottomAnchor.constraint(equalTo: result.bottomAnchor)
])
for subView in view.documentView?.subviews ?? [] {
subView.isUserInteractionEnabled = true
}
result.layoutIfNeeded()
return result
}
}
PKCanvasView is a subclass of UIScrollView and the scaling behavior is simply how the UIScrollView works. There's no workaround for this behavior. I suggest filing an enhancement request using the Feedback Assistant. If you file the request, please post the Feedback number here so we can make sure it gets routed to the right team.
If you're not familiar with how to file enhancement requests, take a look at Bug Reporting: How and Why?