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
Test Whether a Uiview Is in the Middle of Animation
In Firebase, How to Query the Most Recent 10 Child Nodes
Getting Time Elapsed in Objective-C
Objective-C 101 (Retain VS Assign) Nsstring
How to Disable Uitextfield Editing But Still Accept Touch
Hiding Uitabbar When Pushing a Uiview
App Icons Not Included in Build from Xcode
Firebase Undefined Symbols for Architecture X86_64
Uicollectionview's Cell Registerclass in Swift
Swift - Get Local Date and Time
Unexpected Non-Void Return Value in Void Function Swift3
Detecting iPhone 6/6+ Screen Sizes in Point Values
How to Display a Uipopoverview as a Annotation to the Map View? (iPad)
When How to Activate/Deactivate Layout Constraints
Black Screen After Adding Scenedelegate and Updating Info.Plist
Custom Font Not Working Programmatically in Swift
Uicollectionview - Diddeselectitematindexpath Not Called If Cell Is Selected