突然有個需求要求在程式中截圖,調查實驗後後在此分享一下。
先添加頭檔案
#import <QuartzCore/QuartzCore.h>
這裡使用兩種方法測試
一個是私有api的UIGetScreenImage()
一個是UIGraphics的方法
- (UIImage*) takeShot
{
//private api and device only 不支援模拟器哦
extern CGImageRef UIGetScreenImage();//需要先extern
UIImage *p_w_picpath = [UIImage p_w_picpathWithCGImage:UIGetScreenImage()];
UIImageWriteToSavedPhotosAlbum(p_w_picpath,nil,nil,nil);
return p_w_picpath;
}
- (void)viewDidLoad {
[super viewDidLoad];
//plan A.
self.view.backgroundColor = [UIColor redColor];
UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContext(screenWindow.frame.size);
[screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
//plan B:private api and device only
#if !TARGET_IPHONE_SIMULATOR
self.view.backgroundColor = [UIColor greenColor];
[self performSelector:@selector(takeShot) withObject:nil afterDelay:1];
#elif
self.view.backgroundColor = [UIColor clearColor];
#endif
}
圖檔在相冊中檢視,使用之後的效果比較,使用itouch 4,高清螢幕。
UIGraphics的圖檔比較模糊,感覺是按像素畫出來的結果