How to screenshot just part of a screen

为君一笑 提交于 2019-12-13 01:37:02

问题


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.



来源:https://stackoverflow.com/questions/34887164/how-to-screenshot-just-part-of-a-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!