起因:
公司项目需要截图,截长图
问题:
如何截图,截长图,网上的资料往往不是太长,就是没解决问题,甚至有不少bug。
解决办法
下面是我找到最精简的方法
1、截图
import UIKit
extension UIView {
/// 截屏Image
var captureImage: UIImage? {
// 参数①:截屏区域 参数②:是否透明 参数③:清晰度
UIGraphicsBeginImageContextWithOptions(frame.size, true, UIScreen.main.scale)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
调用
let image = view.captureImage
2、长图、大图
用上个方法可以截普通的view,但是scrollView,tableView不行,
截长屏需要改变frame的size为contentSize进行截图,操作之后设置回来即可
import UIKit
extension UIScrollView {
/// 截长屏Image
var captureLongImage: UIImage? {
var image: UIImage? = nil
let savedContentOffset = contentOffset
let savedFrame = frame
contentOffset = .zero
frame = CGRect(x: 0, y: 0,
width: contentSize.width,
height: contentSize.height)
UIGraphicsBeginImageContext(frame.size)
UIGraphicsBeginImageContextWithOptions(
CGSize(width: frame.size.width,
height: frame.size.height),
false,
UIScreen.main.scale)
layer.render(in: UIGraphicsGetCurrentContext()!)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("contentSize == \(contentSize)")
contentOffset = savedContentOffset
frame = savedFrame
return image
}
}
调用
let longImage = tableView.captureLongImage
保存图片
guard let image = tableView.captureLongImage else {
return
}
writeImageToAlbum(image)
fileprivate func writeImageToAlbum(_ image: UIImage) {
MQProgressHUD.showLoading()
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
}
@objc fileprivate func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) {
if let _ = error as NSError? {
print("保存失败,请重试")
} else {
print("保存成功!")
}
}
}