我的情况:
我有一个UIViewController
,其中一个UIButton
和一个UITextField
是第一响应者,单击UIButton
时,我展示了另一个使用自定义过渡的视图控制器(此自定义过渡委托到UIPreentationController
,该容器向containerView边界添加了一个“变暗”视图(黑色背景,alpha为0.5),底部的另一个视图高度为200点,以显示一条消息。
我尝试了很多方法,以防止键盘在此过渡期间/之后从上一屏被关闭而没有运气,但它始终会消失。现在,我想知道是否可以在文本字段成为响应者之后立即拍摄包括键盘的屏幕截图?无需请求其他应用功能。然后,我可以在过渡期间将此图像添加到背景中,并保持“冻结”屏幕的外观。
谢谢您的指导
编辑:
我找到了下面的代码,这些代码带有我想要的代码。但是,键盘背景正在丢失。有人知道为什么吗?
func screenshot() -> UIImage {
let imageSize = UIScreen.main.bounds.size as CGSize;
UIGraphicsBeginImageContextWithOptions(imageSize, true, 0)
let context = UIGraphicsGetCurrentContext()
for obj : AnyObject in UIApplication.shared.windows {
if let window = obj as? UIWindow {
print(window)
if window.responds(to: #selector(getter: UIWindow.screen)) || window.screen == UIScreen.main {
print(window)
// 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!
}
答案 0 :(得分:3)
通过这种方式,还会有键盘。
private func takeScreenshot() {
let snaposhotView: UIView = UIScreen.main.snapshotView(afterScreenUpdates: false)
let renderer: UIGraphicsImageRenderer = UIGraphicsImageRenderer(size: snaposhotView.bounds.size)
let image: UIImage = renderer.image { context in
snaposhotView.drawHierarchy(in: snaposhotView.bounds, afterScreenUpdates: true)
}
// To save in Photos
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
如果要将其用于自定义过渡,并且需要UIImage
,则可以轻松地更改如下代码:
private func takeScreenshot() -> UIImage {
let snaposhotView: UIView = UIScreen.main.snapshotView(afterScreenUpdates: false)
let renderer: UIGraphicsImageRenderer = UIGraphicsImageRenderer(size: snaposhotView.bounds.size)
return renderer.image { context in
snaposhotView.drawHierarchy(in: snaposhotView.bounds, afterScreenUpdates: true)
}
}
答案 1 :(得分:0)
func screenShotMethod() {
let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)
}