源码下载地址:http://download.youkuaiyun.com/detail/liu537192/8520789
效果图:
核心代码:
//
// JLViewController.m
// 04-屏幕截图
//
// Created by Mac on 15-3-21.
// Copyright (c) 2015年 vxinyou. All rights reserved.
//
#import "JLViewController.h"
@interface JLViewController ()
- (IBAction)clip;
@end
@implementation JLViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
/**
* "截图"按钮
*/
- (IBAction)clip {
// 延迟1秒后执行截图功能
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 1,开启基于位图的上下文
// 参数一:新图片的尺寸
// 参数二:新图片是否透明。一般设置为NO:不透明
// 参数三:固定写法:0.0
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
// 2,将控制器view的layer渲染到基于位图的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
// 3,取出图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 4,结束上下文
UIGraphicsEndImageContext();
// 5,保存截图到文件
// 压缩成二进制数据
NSData *data = UIImagePNGRepresentation(newImage);
// 保存到文件
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"new.png"];
[data writeToFile:path atomically:YES];
});
}
@end