如何捕获屏幕视图并共享它?

How do I capture screen view and share it?

我在不同的地方看到过一些帖子,但认为它们没有完全涵盖我正在寻找的内容。

通过点击一个名为 'Share' 的栏按钮项目,我希望我的应用程序截取应用程序中当前视图的屏幕截图并弹出共享 window 以与 Twitter 共享, Facebook 和其他人。

您可以添加分享按钮

var shareButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "shareButtonPressed:")
self.navigationItem.rightBarButtonItem = shareButton

并填充共享选项

func shareButtonPressed(sender: AnyObject) {
    NSLog("shareButton pressed")
    let stringtoshare: String = "This is a string to share"

    //add current screen shot image to share
    let imagetoshare = captureScreen()

    let activityItems: [AnyObject] = [stringtoshare, imagetoshare]
    let activityVC: UIActivityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
    activityVC.excludedActivityTypes = [UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypePostToFacebook, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo]
    self.presentViewController(activityVC, animated: TRUE, completion: { _ in })
}

//捕获屏幕截图图像

func captureScreen() -> UIImage
{

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);

    self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

    var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image
}

如果您在这方面发现任何问题,请告诉我,我无法测试此代码片段(因为我不在系统中),但这是我过去在应用程序中处理的方式。