滚动视图中的大图像捏缩放不起作用

Large image in Scrollview pinch zoom not working

我正在构建一个应用程序,我想在其中显示图像为 1260x1000 的平面图,大于我的视图控制器的大小。我希望用户能够平移图像并放大和缩小,类似于地图在 Mapview 中的行为方式。

下面是我的视图控制器中的代码。当我 运行 模拟器时,图像在平移,但放大和缩小不起作用。关于如何修复我的代码的任何建议都会有所帮助。


class ViewController: UIViewController, UIScrollViewDelegate {
 var scrollView: UIScrollView!
    var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView = UIImageView(image: UIImage(named: "myMap.pdf"))
        scrollView = UIScrollView(frame: view.bounds)
        scrollView.contentSize = imageView.bounds.size
        scrollView.addSubview(imageView)
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.3
        scrollView.maximumZoomScale = 5
        view.addSubview(scrollView)
    }
       func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }


}

你的函数签名有误:

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
}

注意:如果您希望能够在保持基于矢量的渲染的同时缩放 pdf 图像(因此在缩放时不会变得模糊),您可能应该使用 PDFKitPDFView.

将您的 myMap.pdf 文件添加到您的包中... 到您的资产目录中。

import UIKit
import PDFKit

class ZoomingPDFViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let fileURL = Bundle.main.url(forResource: "myMap", withExtension: "pdf") else {
            fatalError("Could not load myMap.pdf!")
        }

        // Add PDFView to view controller.
        let pdfView = PDFView(frame: self.view.bounds)
        pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(pdfView)

        // Load myMap.pdf file from app bundle.
        pdfView.document = PDFDocument(url: fileURL)

        pdfView.autoScales = true
        pdfView.maxScaleFactor = 5.0
        pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit

    }

}