猴子原創(chuàng),歡迎轉載。轉載請注明: 轉載自Cocos2Der-CSDN,謝謝!
原文地址: http://blog.csdn.net/cocos2der/article/details/51780954
今天無意中在百度地圖中截屏線路的時候,頂部出現(xiàn)提示我的截屏信息。這細節(jié)挺好的,省去我后面需要使用該截屏的繁瑣步驟。恰好手頭空閑會,我也寫個玩玩。哈哈哈~~
截屏在iOS7之前是需要使用小技能來獲得用戶截屏事件的,iOS7以后,apple開放了用戶截屏通知事件,所以現(xiàn)在做起來還是挺方便的。
// This notification is posted after the user takes a screenshot (for example by pressing both the home and lock screen buttons)
@available(iOS 7.0, *)
public let UIApplicationUserDidTakeScreenshotNotification: String
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.userDidTakeScreenshot), name: UIApplicationUserDidTakeScreenshotNotification, object: nil)
/// 用戶截屏終了
func userDidTakeScreenshot() {
// 當前屏幕的image
// 注意:為何不直接從相冊讀取截屏圖象
//(萬1用戶直接謝絕可權限你不跪了,何況截屏以后,用戶可不知道你會提示,第1反應肯定謝絕讀取相冊的權限)
let image = imageWithScreenshot()
let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 320, height: 640))
imageView.image = image
self.view.addSubview(imageView)
}
/// 獲得當前屏幕圖片
func imageWithScreenshot() -> UIImage? {
let imageData = dataWithScreenshotInPNGFormat()
return UIImage(data: imageData)
}
/// 截取當前屏幕
func dataWithScreenshotInPNGFormat() -> NSData {
var imageSize = CGSizeZero
let screenSize = UIScreen.mainScreen().bounds.size
let orientation = UIApplication.sharedApplication().statusBarOrientation
if UIInterfaceOrientationIsPortrait(orientation) {
imageSize = screenSize
} else {
imageSize = CGSizeMake(screenSize.height, screenSize.width)
}
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
let context = UIGraphicsGetCurrentContext()
for window in UIApplication.sharedApplication().windows {
CGContextSaveGState(context)
CGContextTranslateCTM(context, window.center.x, window.center.y)
CGContextConcatCTM(context, window.transform)
CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y)
if orientation == UIInterfaceOrientation.LandscapeLeft {
CGContextRotateCTM(context, CGFloat(M_PI_2))
CGContextTranslateCTM(context, 0, -imageSize.width)
} else if orientation == UIInterfaceOrientation.LandscapeRight {
CGContextRotateCTM(context, -CGFloat(M_PI_2))
CGContextTranslateCTM(context, -imageSize.height, 0)
} else if (orientation == UIInterfaceOrientation.PortraitUpsideDown) {
CGContextRotateCTM(context, CGFloat(M_PI))
CGContextTranslateCTM(context, -imageSize.width, -imageSize.height)
}
if window.respondsToSelector(#selector(UIView.drawViewHierarchyInRect(_:afterScreenUpdates:))) {
window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true)
} else {
window.layer.renderInContext(context!)
}
CGContextRestoreGState(context);
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImagePNGRepresentation(image)!
}
注意:為何不直接從相冊讀取截屏圖象?
萬1用戶直接謝絕可權限你不跪了,何況截屏以后,用戶可不知道你會提示,第1反應肯定謝絕讀取相冊的權限。
上一篇 【初探Spring】——Spring IOC(三):初始化過程—Resource定位
下一篇 【原創(chuàng)】NIO框架入門(三):iOS與MINA2、Netty4的跨平臺UDP雙向通信實戰(zhàn)