获取 iOS/swift 中当前屏幕的屏幕截图以进行共享

Get screenshot of current screen in iOS/swift for sharing

我想在我的 phone 上启用一项功能,允许用户单击共享,然后他们就可以向他们的朋友发送一条消息,默认情况下包含该应用程序的图片(就在之前用户点击分享)。我不知道如何做到这一点 - 每当我搜索如何做到这一点时,我得到的都是 tutorials/answers 关于如何在 phone 的照片库中或通过他们的相机共享图像。关于如何做到这一点的任何想法!

UIGraphicsBeginImageContext(self.view.bounds.size)
self.view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

// 从屏幕截图创建图像

UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

//分享图片

var imagesToShare = [AnyObject]()
imagesToShare.append(image)

let activityViewController = UIActivityViewController(activityItems: imagesToShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
presentViewController(activityViewController, animated: true, completion: nil)

要在用户点击“分享”之前分享您的屏幕,首先您需要将屏幕的视图更改为图像并进行分享。

要将视图更改为图像,您可以在代码中添加此扩展程序。

//UIView extension which converts the UIView into an image.
extension UIView {
    func toImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)

        drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

在那里传递您的 ViewController 的观点,例如:

   let imageToShare = self.view.toImage()

    let activityItems : NSMutableArray = []()
       activityItems.addObject(imageToShare)


   let activityVC = UIActivityViewController(activityItems:activityItems as [AnyObject] , applicationActivities: nil)
                self.presentViewController(activityVC, animated: true, completion: nil)

希望对您有所帮助。