ios开发小技巧之摇一摇截屏

1、 监控摇一摇动作

  1> 让当前视图控制器成为第一响应者

    // 必须先让当前视图控制器成为第一响应者才能响应动作时间
    [self becomeFirstResponder];

  2> 实现响应方法-继承自UIResponder的方法

1 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
2 {
3     // 如果动作类型是摇一摇[震动]
4     if (motion == UIEventSubtypeMotionShake) {
5         
6         // 调用截屏方法
7         [self snapshot];
8     }
9 }

2、 截屏 

  注意: 1 > 在获取图像时,必须先开启图像上下文,再获取上下文

      2 > 保存成功后执行的方法必须是固定格式的,也就是下面代码所展示的格式

 1 #pragma mark - 点击截屏按钮
 2 - (IBAction)snapshot
 3 {
 4     // 1. 开启图像上下文[必须先开开启上下文再执行第二步,顺序不可改变]
 5     UIGraphicsBeginImageContext(self.view.bounds.size);
 6     
 7     // 2. 获取上下文
 8     CGContextRef context = UIGraphicsGetCurrentContext();
 9     
10     // 3. 将当前视图图层渲染到当前上下文
11     [self.view.layer renderInContext:context];
12     
13     // 4. 从当前上下文获取图像
14     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
15     
16     // 5. 关闭图像上下文
17     UIGraphicsEndImageContext();
18     
19     // 6. 保存图像至相册
20     UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
21 }
22 
23 #pragma mark 保存完成后调用的方法[格式固定]
24 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
25 {
26     if (error) {
27         NSLog(@"error-%@", error.localizedDescription);
28     }else{
29         NSLog(@"保存成功");
30     }
31 }

以上就是摇一摇截屏的简单使用!

原文地址:https://www.cnblogs.com/liufeng24/p/3504429.html