Swift:如何保存视图的屏幕截图以及该视图下方的所有视图?



我需要制作表格视图的屏幕截图(它有一个清晰的背景(。但在它下面,我还有一个图像视图和模糊视图。我需要获取所有这些视图的屏幕截图。

我尝试了不同的解决方案,但它们没有捕获底部视图。有什么办法可以做到这一点吗?

另外,我不需要屏幕的完整屏幕截图。仅受表视图限制的边界。我想,我有一些选择如何制作完整的屏幕截图,但它不适用于视图

我试过了:

1:

func snapshot(of rect: CGRect? = nil) -> UIImage? {
// snapshot entire view
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
drawHierarchy(in: bounds, afterScreenUpdates: true)
let wholeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// if no `rect` provided, return image of whole view
guard let image = wholeImage, let rect = rect else { return wholeImage }
// otherwise, grab specified `rect` of image
let scale = image.scale
let scaledRect = CGRect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale)
guard let cgImage = image.cgImage?.cropping(to: scaledRect) else { return nil }
return UIImage(cgImage: cgImage, scale: scale, orientation: .up)
}

阿拉伯数字:

UIGraphicsBeginImageContext(tableView.frame.size)
tableView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image1 = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

我的层次结构是:

  • 基本用户界面

    • UIImage视图与图像

      • UIBlurEffect

        • UITable视图具有清晰的背景,显示图表

如果我理解你的问题,你想要一个真正的屏幕截图,而不是整个屏幕。因此,请截取原始屏幕截图:

let snap = UIApplication.shared.keyWindow!.snapshotView(afterScreenUpdates: true)
snap.frame = view.bounds // or something, if necessary

将蒙版应用于屏幕截图,其框架等于表格视图的边界:

let mask = CALayer()
mask.frame = tableView.frame.bounds
mask.backgroundColor = UIColor.white.cgColor
snap.layer.mask = mask

最新更新