I am trying to take a screenshot (after a button press) of only half of the viewController size (positioned right in the middle).
I know that I can take a screenshot of the whole view like this:
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, true, 0.0)
self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
I have looked through stackoverflow, but it still doesn't work.
This for instance doesn't work with these error messages:
UIGraphicsBeginImageContextWithOptions(CGSize(100, 100), false, 0);
Error: Argument labels '(_:, _:)' do not match any available overloads
self.view.drawViewHierarchyInRect(CGRect(-50,-5-,view.bounds.size.width,view.bounds.size.height), afterScreenUpdates: true)
Error: Argument labels '(_:, _:, _:, _:)' do not match any available overloads
var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
How can I create a screenshot of exactly half of the viewController?
Try This.For Swift
extension UIView {
func screenshot() -> UIImage {
return UIGraphicsImageRenderer(size: bounds.size).image { _ in
drawHierarchy(in: CGRect(origin: .zero, size: CGSize(width: bounds.size.width/2.0, height: bounds.size.height/2.0)), afterScreenUpdates: true)
}
}
}
Use.
let image = view.screenshot()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.