简介:
在程序开发中,有时候需要截取屏幕上的某一块内容.
完成截屏功能的核心代码:- (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内容:
第一次保存到相册中, 系统会提醒用户, 点击允许后, 如果出现保存成功的弹框, 就能在相册中找到刚才的截图了