/* 点击模拟器 在左上边的一栏里 Hardware中Shake Gesture 为摇一摇command+shift+z 不一定好使 */
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height)];
// image.image = [UIImage imageNamed:@"NQN$BKVL()WW~B(2`O$2PAP.jpg"];
// image.image = [UIImage imageNamed:@"28JE6Y@S8GXXRL~MKNUYX9T.jpg"];
image.image = [UIImage imageNamed:@"专属姣儿.jpg"];
[self.view addSubview:image];
[image release];
/*
** 1、监控摇一摇动作
*/
#pragma mark 1, 让当前视图控制器成为第一响应者
// 必须先让当前视图控制器成为第一响应者才能响应动作时间
[self becomeFirstResponder];
}
#pragma mark 2, 实现响应方法-继承自UIResponder的方法
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
// 如果动作类型是摇一摇[震动]
if (motion == UIEventSubtypeMotionShake) {
// 调用截屏方法
[self snapshot];
}
}
/*
** 2、截屏
注意: 1, 在获取图像时,必须先开启图像上下文,再获取上下文
2, 保存成功后执行的方法必须是固定格式的,也就是下面代码所展示的格式
*/
#pragma mark - 点击截屏按钮
- (IBAction)snapshot
{
NSLog(@"摇了");
// 1. 开启图像上下文[必须先开开启上下文再执行第二步,顺序不可改变]
UIGraphicsBeginImageContext(self.view.bounds.size);
// 2. 获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 3. 将当前视图图层渲染到当前上下文
[self.view.layer renderInContext:context];
// 4. 从当前上下文获取图像
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 5. 关闭图像上下文
UIGraphicsEndImageContext();
// 6. 保存图像至相册
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
#pragma mark 保存完成后调用的方法[格式固定]
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if (error) {
NSLog(@"error-%@", error.localizedDescription);
}else{
NSLog(@"保存成功");
}
}
/* 可能会有点慢 但却实现了简单地截屏 */