有没有办法将UIView转换为可以通过电子邮件发送的图像?

时间:2017-10-16 10:55:54

标签: swift swift3 uiview uiimage

我希望将UIView保存或转换为可以通过电子邮件发送为图像的图像。

我试过了:

UIGraphicsBeginImageContext(self.view.bounds.size);
    self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

但是我不能回拨screenShot,因为它在不同的功能中是必需的。

func configureMailController() -> MFMailComposeViewController {
    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self

    mailComposerVC.setToRecipients(["emailaddress"email.com"])
    mailComposerVC.setSubject("ScreenShot")
    mailComposerVC.setMessageBody("Here's the image", isHTML: true)
    let imageData: NSData = UIImagePNGRepresentation(screenShot.image)!
    mail.addAttachmentData(imageData, mimeType: "image/png", fileName: "imageName")
    return mailComposerVC
}

我不确定即使它没有返回错误也不会有效,但这是我能想到的唯一方法。

1 个答案:

答案 0 :(得分:1)

通过将所有代码放在同一个函数中,它确实有效。

这是我使用的代码:

func configureMailController() -> MFMailComposeViewController {
    UIGraphicsBeginImageContext(self.view.bounds.size);
    self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self

    mailComposerVC.setToRecipients(["emailaddress@email.com"])
    mailComposerVC.setSubject("Form")
    mailComposerVC.setMessageBody("Here's the image", isHTML: true)
    let imageData: NSData = UIImagePNGRepresentation(screenShot!)! as NSData
    mailComposerVC.addAttachmentData(imageData as Data, mimeType: "image/png", fileName: "imageName")
    return mailComposerVC
}