【发布时间】:2021-08-19 19:57:19
【问题描述】:
我希望下面的 swift 代码截取 2 个屏幕截图。一个屏幕截图应该是从顶部到 20% 的整个视图,另一个是从 20% 到 100% 高度的整个视图。我创建了一个图像,显示了我正在寻找的内容。图像应该有不同的比例。我真的不知道还要添加什么。
var drawbox = Canvas()
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
@objc func saving(){
let vex = self.view.screenshot(for: drawbox.frame, clipToBounds: true)
UIImageWriteToSavedPhotosAlbum(vex, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
extension UIView {
/// Takes a screenshot of a UIView, with an option to clip to view bounds and place a waterwark image
/// - Parameter rect: offset and size of the screenshot to take
/// - Parameter clipToBounds: Bool to check where self.bounds and rect intersect and adjust size so there is no empty space
/// - Parameter watermark: UIImage of the watermark to place on top
func screenshot(for rect: CGRect, clipToBounds: Bool = true, with watermark: UIImage? = nil) -> UIImage {
var imageRect = rect
if clipToBounds {
imageRect = bounds.intersection(rect)
}
return UIGraphicsImageRenderer(bounds: imageRect).image { _ in
drawHierarchy(in: CGRect(origin: .zero, size: bounds.size), afterScreenUpdates: true)
watermark?.draw(in: CGRect(origin: imageRect.origin, size: CGSize(width: 32, height: 32))) // update origin to place watermark where you want, with this update it will place it in top left or screenshot.
}
}
}
【问题讨论】: