Screenshot Showing Up Blank - Swift

Screenshot showing up blank - Swift

update: Xcode 8.2.1 • Swift 3.0.2

You need to add the import statement and this extension to your game scene:

import UIKit 

extension UIView {
var snapshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
defer { UIGraphicsEndImageContext() }
drawHierarchy(in: bounds, afterScreenUpdates: true)
return UIGraphicsGetImageFromCurrentImageContext()
}
}

let myImage = view?.snapshot

Why does the screenshot show just white when I'm trying to take a screenshot of my app programmatically in Swift?

Render and capture an UIView named view:

UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)
view.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();

Remember that UIWindow is a view too.
You can test in the simulator saving to the desktop with this function:

public func saveImageToDesktop(image : UIImage, name : String)
{
let basePath = NSString(string: "~/Desktop").stringByExpandingTildeInPath
let path = "\(basePath)/\(name).png"
UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
}

Taking screenshot using Swift 5 returns a black image and not the app's screen

Try changing

 afterScreenUpdates: false

To

 afterScreenUpdates: true

That way there will be some drawing to snapshot.



Related Topics



Leave a reply



Submit