How to take screenshot of AVplayerLayer. I tried with the following code it works well, it captures the entire view as it was
func screenShotMethod() {
let window = UIApplication.shared.delegate!.window!!
//capture the entire window into an image
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
let windowImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//now position the image x/y away from the top-left corner to get the portion we want
UIGraphicsBeginImageContext(view.frame.size)
windowImage?.draw(at: CGPoint(x: -view.frame.origin.x, y: -view.frame.origin.y))
let croppedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext();
//embed image in an imageView, supports transforms.
let resultImageView = UIImageView(image: croppedImage)
UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil)
}
But the problem is when i tried the same code running on iPhone(device) it returns black image.i don't know what was wrong
Any suggestions would be greatly helpful!
Here is the code that is working for me in swift 4:
A few days ago, we also ran into the same issue. Where, if we take the screenshot of a screen which has a video player in it; The screenshot looks fine in the simulator.But, on the device, it was a black screen.
After a lot of attempts, I failed and finally end up with a patch (not sure if it is a correct way of solving the problem). But, the solution did the trick and I was able to get the screenshot on the device as well and simulator as well.
Following is a way I used to solve the issue.
1 -> Get a single frame at current time from the video (Public method is already available for this)
2 -> Use this thumbnail in the place of CALayer (add it to hierarchy)
3 -> Once we are done remove the thumbnail from the memory (remove from hierarchy)
Following is a demo sample for the same (The given solution is in Objective-c though the question asked is in Swift).
Objective - C solution
Swift solution