gpt4 book ai didi

ios - 以编程方式在 swift 上截图

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:28 26 4
gpt4 key购买 nike

当我快速按下一个按钮时,我正在尝试截取整个 View 。问题是,当我截屏时,有些部分被切断了,比如顶部...

enter image description here

被截断的其他部分是我在屏幕底部的容器 View 。它包含一个开关、一个文本字段和一个按钮。这是我用来截屏的代码......

func screenShotMethod() {
let layer = UIApplication.shared.keyWindow!.layer
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);

layer.render(in: UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(screenshot!, nil, nil, nil)
}

这是我用来创建容器 View 的代码...

lazy var inputContainerView: UIView = {

let containerView = UIView()
containerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)
containerView.backgroundColor = UIColor.white
//Other things...

override var inputAccessoryView: UIView? {
get {
return inputContainerView
}
}

override var canBecomeFirstResponder : Bool {
return true
}

这就是结局图像的样子...... enter image description here

那我该怎么做才能解决呢?谢谢!

最佳答案

如果您具有某种 Objective-C 知识,那么这里就是您想要的答案。

打开这个Link并遵循遍历所有 View 层次结构的最后一个答案,并逐行注释以完全理解代码。

图像最终被转换为NSDataUIImage。如果你仍然感到困惑,那么我可以将它转换成 swift,但首先你自己尝试一下。

这是该答案的 Swift 代码。

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

关于ios - 以编程方式在 swift 上截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41308685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com