使用Cocos2D / SpriteBuilder时,使用UIGraphicsGetImageFromCurrentImageContext拍摄的ScreenShot为空白

时间:2018-11-21 09:09:33

标签: swift screenshot spritebuilder

使用按钮和以下代码为我的应用程序截屏很麻烦:

func takeAScreenshot() {
    var screenshotImage :UIImage?
    let layer = UIApplication.shared.keyWindow!.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
    let context = UIGraphicsGetCurrentContext()
    layer.render(in:context!)
    screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    if let image = screenshotImage, true {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }
}

每个屏幕截图均为空白。 我已经尝试了在其他stackOverflow问题上找到的几个代码示例,但是每次都是空白或黑色屏幕截图。

2 个答案:

答案 0 :(得分:0)

使用这些功能

import UIKit
import AudioToolbox

/// Takes the screenshot of the screen and returns the corresponding image
///
/// - Parameter shouldSave: Boolean flag asking if the image needs to be saved to user's photo library. Default set to 'true'
/// - Returns: (Optional)image captured as a screenshot
func takeScreenshot(_ shouldSave: Bool = true) -> UIImage? {
    var screenshotImage :UIImage?
    let layer = UIApplication.shared.keyWindow!.layer
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
    guard let context = UIGraphicsGetCurrentContext() else {return nil}
    layer.render(in:context)
    screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    if let image = screenshotImage, shouldSave {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
    }
    return screenshotImage
}

//Take Screenshot
func takeScreenShot(viewController: UIViewController) {
     let image = self.takeScreenshot(true)
     var imagesToShare = [AnyObject]()
     imagesToShare.append(image!)

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

答案 1 :(得分:-1)

open func takeScreenshot(_ shouldSave: Bool = true) -> UIImage? {
        var screenshotImage :UIImage?
        let layer = UIApplication.shared.keyWindow!.layer
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
        guard let context = UIGraphicsGetCurrentContext() else {return nil}
        layer.render(in:context)
        screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        if let image = screenshotImage, shouldSave {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        }

        return screenshotImage


    }