簡介:
在程序開發中,有時候需要截取屏幕上的某一塊內容.
完成截屏功能的核心代碼:- (void)renderInContext:(CGContextRef)ctx;調用某個view的layer的renderInContext:方法即可
storyboard界面搭建:
代碼:
#import "ViewController.h"
#import "MBProgressHUD+MJ.h"
@interface ViewController ()
- (IBAction)cutScreen;
@end
@implementation ViewController
- (IBAction)cutScreen{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 開啓上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 將view繪製到圖形上下文中
[self.view.layer renderInContext:ctx];
// 取出圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 結束上下文
UIGraphicsEndImageContext();
// 7.將image對象壓縮爲PNG格式的二進制數據
// NSData *data = UIImagePNGRepresentation(newImage);
// 8.寫入文件
// NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"new.png"];
// [data writeToFile:path atomically:YES];
// 9. 保存到相冊中
//將截屏保存到相冊
UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
});
}
// 系統建議使用的方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if (error) {
[MBProgressHUD showError:@"保存失敗"];
}else
{
[MBProgressHUD showSuccess:@"保存成功"];
}
}
API內容:
第一次保存到相冊中, 系統會提醒用戶, 點擊允許後, 如果出現保存成功的彈框, 就能在相冊中找到剛纔的截圖了