使用iOS手機的同學,在平時操作APP的時候肯定會遇到這種情況,當你在試用期間截圖時,APP會自動彈出你的截圖,并且提示你分享或者反饋。這種效果看起來很牛逼,但實際上是一個十分容易實現(xiàn)的需求,因為在iOS7以后蘋果為大家提供了一個獲取截圖的通知,會在截圖后調(diào)用:
OC:UIApplicationUserDidTakeScreenshotNotification
Swift:UIApplicationUserDidTakeScreenshot
獲取到截圖的通知有什么用呢?有些同學會想,是不是此時調(diào)用系統(tǒng)的相冊,獲取相冊的最后一張圖片。這個方法可以,只不過太笨了,你還要寫一堆調(diào)用系統(tǒng)相冊的方法,寫到最后會讓你感到淡淡的悲傷。其實最簡單和高效的方法,就是在接收到通知的同時,直接截取手機屏幕內(nèi)的圖片。高效又方便,不用調(diào)用一大堆系統(tǒng)方法,接下來,我就給大家將Swift的代碼上一下。
import UIKit
class ViewController: UIViewController {
//隨便加的一個imageView
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
///添加通知
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.userDidTakeScreenshot), name: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil)
}
deinit {
///移除通知
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil)
}
//截屏通知
@objc func userDidTakeScreenshot() {
//獲取屏幕圖片
let image = takeScreenshot()
imageView.image = image
}
/// 截取當前屏幕
func takeScreenshot() -> UIImage {
var imageSize = CGSize.zero
let screenSize = UIScreen.main.bounds.size
let orientation = UIApplication.shared.statusBarOrientation
if UIInterfaceOrientationIsPortrait(orientation) {
imageSize = screenSize
} else {
imageSize = CGSize(width: screenSize.height, height: screenSize.width)
}
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
if let context = UIGraphicsGetCurrentContext() {
for window in UIApplication.shared.windows {
context.saveGState()
context.translateBy(x: window.center.x, y: window.center.y)
context.concatenate(window.transform)
context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
if orientation == UIInterfaceOrientation.landscapeLeft {
context.rotate(by: .pi / 2)
context.translateBy(x: 0, y: -imageSize.width)
} else if orientation == UIInterfaceOrientation.landscapeRight {
context.rotate(by: -.pi / 2)
context.translateBy(x: -imageSize.height, y: 0)
} else if orientation == UIInterfaceOrientation.portraitUpsideDown {
context.rotate(by: .pi)
context.translateBy(x: -imageSize.width, y: -imageSize.height)
}
if window.responds(to: #selector(UIView.drawHierarchy(in:afterScreenUpdates:))) {
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
} else {
window.layer.render(in: context)
}
context.restoreGState()
}
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image {
return image
} else {
return UIImage()
}
}
}
其實很簡單的朋友們,不過最后還有一點點小小的建議。如果你想在APP內(nèi)全局都實現(xiàn)這個功能,我建議你將這個通知放在BaseController的viewDidLoad中,大家只要記得在控制器銷毀時移除通知就行了。這樣在全局都可以實現(xiàn)截圖分享、截圖反饋等功能。ok,喜歡的話可以點一波收藏。