如何在 xcode/swift 中分享 "screenshot" 整个滚动视图?

How to share "screenshot" a entire scrollview in xcode/swift?

谁能告诉我在哪里添加框架大小或边界以捕获整个滚动视图,它的宽度设置为任意,高度为 2200p。 导入 UIKit

class ViewController: UIViewController {

@IBAction func shareButton(_ sender: Any) {

        UIGraphicsBeginImageContextWithOptions(view!.frame.size, false, 0.0)
        view!.drawHierarchy(in: view!.frame, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();

        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)

        let activityVC = UIActivityViewController(activityItems: [image!], applicationActivities: nil)

        let vc = self.view?.window?.rootViewController

        activityVC.popoverPresentationController?.sourceView = vc?.view
        activityVC.popoverPresentationController?.sourceView = self.view
        self.present(activityVC, animated: true, completion: nil)

}

}

这就是我的代码,它确实截取了屏幕截图,但只有屏幕上的内容和 UIActivityController 出现了。不用担心每次按下后重命名它或我可以与哪些其他应用程序共享。

我看过这里的其他 post 并遇到崩溃或无数错误,它们已经过时了。

感谢您的帮助。

您遇到的问题是因为您将图形上下文大小设置为视图的大小,我猜是您的视图控制器 'view' 属性 是相同的大小与您的屏幕一致。

我首先将所有滚动视图内容放入内容视图(只是一个 UIView 作为容器),然后将该内容视图放入滚动视图中。

然后我会在 UIView 上创建一个类别来创建任何 UIView 的图像:

public extension UIView {
    /**
        Captures view and subviews in an image
    */
    func snapshotViewHierarchy() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
        let copied = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return copied
    }
}

并在内容视图上调用该函数,因此内容视图使用它自己的边界而不是 viewController.view 的框架在上下文中呈现。

// get a screenshot of just this view
guard let snapshot = myVc.contentView.snapshotViewHierarchy() else {
    return
}

// save photo
UIImageWriteToSavedPhotosAlbum(snapshot, nil, nil, nil)

// do other stuff... etc...

这是一个 link 的简单演示项目,它在 2200 点高的滚动视图中拍摄视图快照,并将该视图作为图像保存到用户照片卷中。

Demo Project Github link - https://github.com/appteur/ios_scrollview_image