iOS 摇一摇截屏功能的实现

1,982 阅读1分钟
原文链接: www.jianshu.com

demo地址:github.com/GoldenRocki…
如果感兴趣的话,可以参考一下

1.摇一摇功能的实现:

在viewDidLoad方法中调用:

[[UIApplicationsharedApplication]setApplicationSupportsShakeToEdit:YES];

在viewWillAppear方法中调用:

[selfbecomeFirstResponder];

为了防止意外发生,需要在viewWillDisappear方法中调用:

[selfresignFirstResponder];

实现和摇一摇相关的三个方法:

#pragma mark - ShakeToEdit
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //手机震动
    dispatch_queue_t queue = dispatch_queue_create("shake", NULL);
    dispatch_async(queue, ^{
        [self shake];
    });

}

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

}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    UIImage *image = [self  screenshot];

    if(image){
        [ShowView showWithImage:image AndSaveClick:^{
            [self saveImageToPhotos:image];
        }];
    }
}

2.屏幕截图功能的实现:

#pragma mark - ScreenShot
-(UIImage *)screenshot{

    UIView *view = self.view;
    //  float scale = [[UIScreenmainScreen] scale];//得到设备的分辨率
    //  scale = 1; 的时候是代表当前设备是320*480的分辨率(就是iphone4之前的设备)
    //  scale = 2; 的时候是代表分辨率为640*960的分辨率

    //绘图
    //第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了,关键就是第三个参数。
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
    //渲染
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    //生产图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    return image;
}

3.按钮点击事件添加block的方法:
可参考demo中ShowView.m的实现