有時(shí)候單純的截圖并不足以滿足要求,我們需要在保證截圖內(nèi)容的前提下,額外添加一些信息,比如用戶信息,日期,產(chǎn)品二維碼等。
截長圖
由于我用到了導(dǎo)航欄,但是導(dǎo)航欄又是不截進(jìn)去的,所以需要調(diào)整frame,截圖完成之后再恢復(fù)(恢復(fù)到用戶滑動(dòng)的位置)。
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是你最后生成圖片的大小,相當(dāng)于你在一張新的圖片上把你的要的東西全放上去。
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)
//位置需要自己設(shè)置
text.draw(in: CGRect(x: 69 * scale, y: 23 * scale, width: textSize.width, height: textSize.height), withAttributes: att)
UIGraphicsEndImageContext()
圖片合成
其實(shí)與文字是一樣的,其實(shí)兩者是一起的,都是Begin和End之間進(jìn)行。
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添加相冊訪問權(quán)限,否則可能崩潰)
UIImageWriteToSavedPhotosAlbum(finalImage, nil, nil, nil);
//提示
SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Saved", comment:""))
通過系統(tǒng)自帶的分享保存
let barButtonItem=UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action, target: self, action: #selector(Share))
//此處使用的圖標(biāo)UIBarButtonSystemItem是一個(gè)系統(tǒng)自帶的枚舉
self.navigationItem.rightBarButtonItem = barButtonItem
Share函數(shù)
然后在系統(tǒng)彈出的分享頁面中,進(jìn)行不同的操作,這些圖片和文字就會相應(yīng)的顯示。
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
})
效果

分享效果