有时候单纯的截图并不足以满足要求,我们需要在保证截图内容的前提下,额外添加一些信息,比如用户信息,日期,产品二维码等。
截长图
由于我用到了导航栏,但是导航栏又是不截进去的,所以需要调整frame,截图完成之后再恢复(恢复到用户滑动的位置)。
var offset = scrollView.contentOffset
UIGraphicsBeginImageContextWithOptions(CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height), true,UIScreen.main.scale)
var oldFrame = scrollView.frame
scrollView.frame = CGRect(origin: CGPoint(x: 0, y: (self.navigationController?.navigationBar.frame.size.height)! + UIApplication.shared.statusBarFrame.height), size: CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height))
scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageRef = viewImage?.cgImage
let sendImage = UIImage.init(cgImage: imageRef!);
文字添加
注意要*scale,Size是你最后生成图片的大小,相当于你在一张新的图片上把你的要的东西全放上去。
UIGraphicsBeginImageContext(size)
//用户名文字属性
let att = [NSAttributedString.Key.foregroundColor:UIColor.black,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 17 * scale),NSAttributedString.Key.backgroundColor:UIColor.clear,NSAttributedString.Key.kern: -0.08] as [NSAttributedString.Key : Any]
//文字大小
var text = NSString(string: "XXXX")
let textSize = text.size(withAttributes: att)
//位置需要自己设置
text.draw(in: CGRect(x: 69 * scale, y: 23 * scale, width: textSize.width, height: textSize.height), withAttributes: att)
UIGraphicsEndImageContext()
图片合成
其实与文字是一样的,其实两者是一起的,都是Begin和End之间进行。
UIGraphicsBeginImageContext(size)
image.draw(in: CGRect(x: 16 * scale, y: 20 * scale, width: 45 * scale, height: 45 * scale))
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Image
保存(直接保存)
//保存图片到照片库 (记得在info.plist添加相册访问权限,否则可能崩溃)
UIImageWriteToSavedPhotosAlbum(finalImage, nil, nil, nil);
//提示
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Saved", comment:""))
通过系统自带的分享保存
let barButtonItem=UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action, target: self, action: #selector(Share))
//此处使用的图标UIBarButtonSystemItem是一个系统自带的枚举
self.navigationItem.rightBarButtonItem = barButtonItem
Share函数
然后在系统弹出的分享页面中,进行不同的操作,这些图片和文字就会相应的显示。
let textToShare = "XXXX"
let imageToShare = screenView()
let items = [textToShare, imageToShare] as [Any]
let activityVC = UIActivityViewController(
activityItems: items,
applicationActivities: nil)
activityVC.completionWithItemsHandler = { activity, success, items, error in
if(success == true){
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Saved", comment:""))
}
}
self.present(activityVC, animated: true, completion: { () -> Void in
})