How to screenshot just part of a screen

2019-08-08 15:27发布

问题:

I need to crop an image to a rectangle with a height of 25 and a width the length of the screen.

I have the image ready and positioned in the center of the screen. I'd like to screenshot ONLY the rectangle.

I followed this answer, but it does not seem to be working for me for some reason.

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.view.frame.width,25), false, 0)

    self.view.drawViewHierarchyInRect(CGRectMake(self.view.frame.width,25,view.bounds.size.width,view.bounds.size.height), afterScreenUpdates: true)

    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    statusImage = image

回答1:

You are using wrong coordinates. With your code, the drawing starts at the top right corner of the view and draws void space at the right side of it. You should use 0 as X value and a negative Y value. For example, if you want to screenshot a bar starting at Y=50, you should use:

self.view.drawViewHierarchyInRect(CGRectMake(0, -50, view.bounds.size.width, view.bounds.size.height), afterScreenUpdates: true)

If you want to draw from the top of the view, just put 0 as Y value as well.