我的扩展方法现在在视图控制器中截取整个uiview的屏幕快照。我想使用相同的函数来做同样的事情,只获取uiview的一个精确区域,而不是整个视图。具体来说,我想捕捉x:0,y:0,长度200,高度200,
func screenshot() -> UIImage {
let imageSize = UIScreen.main.bounds.size as CGSize;
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
let context = UIGraphicsGetCurrentContext()
for obj : AnyObject in UIApplication.shared.windows {
if let window = obj as? UIWindow {
if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main {
// so we must first apply the layer's geometry to the graphics context
context!.saveGState();
// Center the context around the window's anchor point
context!.translateBy(x: window.center.x, y: window.center
.y);
// Apply the window's transform about the anchor point
context!.concatenate(window.transform);
// Offset by the portion of the bounds left of and above the anchor point
context!.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x,
y: -window.bounds.size.height * window.layer.anchorPoint.y);
// Render the layer hierarchy to the current context
window.layer.render(in: context!)
// Restore the context
context!.restoreGState();
}
}
}
let image = UIGraphicsGetImageFromCurrentImageContext();
return image!
}
最佳答案
怎么样:
extension UIView {
func screenshot(for rect: CGRect) -> UIImage {
return UIGraphicsImageRenderer(bounds: rect).image { _ in
drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
}
}
}
这使它更具可重用性,但如果需要,可以将其更改为硬编码值。
let image = self.view.screenshot(for: CGRect(x: 0, y: 0, width: 200, height: 200))
关于swift - 如何使用扩展市场保存裁剪后的uiview屏幕截图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58383080/