我使用Xcode Swift 3和WKWebView来显示网站。然后我尝试使用我在互联网上找到的以下代码来截取网站。有些网站在网站的顶部或底部附带固定菜单栏。因此,当我滚动网站时,菜单栏不随浏览器移动而固定在屏幕上。问题是这个网站的固定菜单栏出现在我的截图上。有没有办法在没有固定菜单栏的情况下制作屏幕截图?在此先感谢您的帮助。
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)
}