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

时间:2017-04-12 05:16:53

标签: ios swift screenshot

我想在我的手机上启用一项功能,允许用户点击共享,然后他们就可以向他们的朋友发送一条消息,默认情况下包含应用的图片(在用户点击共享之前)。我无法弄清楚如何做到这一点 - 每当我搜索如何做到这一点时,我得到的是关于如何在手机的照片库或他们的相机中共享图像的教程/答案。关于如何做到这一点的任何想法!

3 个答案:

答案 0 :(得分:7)

//从截图

创建图像
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)

答案 1 :(得分:4)

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

答案 2 :(得分:2)

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

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

//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)

我希望这可以帮助你。