2017-09-28 23 views
0

我正在尝试只有一半viewController大小(位于中间位置)的截图(按下按钮后)。Swift:如何截取只有一半的视图?

我知道我可以把整个视图的屏幕截图如下:

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, true, 0.0) 
    self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: false) 
    let img = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 

我已经通过计算器看去,却仍然无法正常工作。

例如,这不符合这些错误信息的工作:

UIGraphicsBeginImageContextWithOptions(CGSize(100, 100), false, 0); 

错误:参数标签 '(_ _ :, :)' 不匹配任何可用的重载

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

错误:参数标签'(_ :, _ :, _ :, _ :)'与任何可用的过载不匹配

var image:UIImage = UIGraphicsGetImageFromCurrentImageContext(); 

如何创建viewController的一半截图?

+2

'CGRectMake'已被重命名为'的CGRect(X:,Y:,宽:,高度:)' – Tj3n

+0

感谢。我已经编辑了这个问题,现在我得到了参数标签'(_ :, _ :, _ :, _ :)'不匹配任何可用重载的错误。 – RjC

+0

您将需要编写变量名称,如'x:-50,y:-5' .... – Tj3n

回答

0

尝试This.For斯威夫特

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) 
     } 
    } 

} 

使用。

let image = view.screenshot()