摇一摇截图,给测试的福利

公司测试反应,有时候出现问题来不及截图..所以写个摇一摇截图

方法写在UIViewController的分类里,无需调用,立即生效

#import "UIViewController+ShakeAndCutter.h"

@implementation UIViewController (ShakeAndCutter)

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    [self snapshot];
}


- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"End");
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"Cancel");
}


- (void)snapshot
{
    // 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(@"保存成功");
    }
}

需要注意:在plist中添加
Privacy - Photo Library Usage Description
访问相册提醒

你可能感兴趣的:(摇一摇截图,给测试的福利)