I have a screenshot of the entire screen, screenshot
, generated using the following:
let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.renderInContext(UIGraphicsGetCurrentContext())
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
I'd like to crop it so that the tab bar is not included, and I tried using the following code:
let crop = CGRectMake(0, 0, //"start" at the upper-left corner
self.view.bounds.width, //include half the width of the whole screen
self.view.bounds.height + self.navigationController!.navigationBar.frame.height) //include the height of the navigationBar and the height of view
let cgImage = CGImageCreateWithImageInRect(screenshot.CGImage, crop)
let image: UIImage = UIImage(CGImage: cgImage)!
This code results in image
showing just a small portion of the screen, a rectangle starting at the upper-left corner of the screen (0, 0), and extending right for less than half the width of the screen, then downward for less than half the height of the screen. I'd like, though, for it to include the entire screen, except for the region occupied by the tab bar. Is there a such a way to crop it?
According to this
You will need to have a crop function like this. You may need adjust the calculation of the
bottomBarHeight
You have two options here: First, you can take the screenshot using
UIApplication.sharedApplication().keyWindow
then we will have this:So, you will have to crop the image like this:
The second option is to take the screenshot directly of your view, like this:
In this case, you don't need to crop the navigationBar.
This is a sample code at github https://github.com/gazolla/crop
My answer in Swift 4.2, the steps are in the comments above the code in the function
getScreenshot()
This is also the Swift 4.2 version of the accepted answer:
swift:
obj-c:
I think your crop
CGRect
is wrong.X: 0 and Y: 0 - start at 0, 0 respectively.
Width: Capture the view's entire width
Height: The entire view's height plus the height of the
UINavigationBar
minus the height of theUITabBar
.