使用OC进行iOS截屏,同时保证清晰度
生活随笔
收集整理的這篇文章主要介紹了
使用OC进行iOS截屏,同时保证清晰度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一般情況下我們使用如下代碼進行截屏:
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; UIGraphicsBeginImageContext(screenWindow.frame.size); [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();但是會發現獲取的截屏圖片模糊,不如系統截屏清晰。
我們需要關注下這個方法:
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
其中,scale是縮放因子。在UIGraphicsBeginImageContext方法中,縮放因子默認是1.0。
之所以生成的圖片不清晰,問題就出在scale上。Retina屏幕的實際像素是邏輯像素的兩倍,Plus是三倍,所以我們需要手動指定scale。
1、我們可以使用0.0,0.0的意思就是自動調整縮放因子以適配顯示屏。
2、問你可以使用[UIScreen mainScreen].scale這個值來動態指定當前設備的縮放因子。
正確的截屏代碼如下:
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; UIGraphicsBeginImageContextWithOptions(screenWindow.frame.size, NO, [UIScreen mainScreen].scale); [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; UIGraphicsBeginImageContext(screenWindow.frame.size); [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();但是會發現獲取的截屏圖片模糊,不如系統截屏清晰。
我們需要關注下這個方法:
UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
其中,scale是縮放因子。在UIGraphicsBeginImageContext方法中,縮放因子默認是1.0。
之所以生成的圖片不清晰,問題就出在scale上。Retina屏幕的實際像素是邏輯像素的兩倍,Plus是三倍,所以我們需要手動指定scale。
1、我們可以使用0.0,0.0的意思就是自動調整縮放因子以適配顯示屏。
2、問你可以使用[UIScreen mainScreen].scale這個值來動態指定當前設備的縮放因子。
正確的截屏代碼如下:
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow]; UIGraphicsBeginImageContextWithOptions(screenWindow.frame.size, NO, [UIScreen mainScreen].scale); [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
總結
以上是生活随笔為你收集整理的使用OC进行iOS截屏,同时保证清晰度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql索引背后的数据结构_图解Mys
- 下一篇: 归档和解档-Archiver