ios 长按截图

//添加点击方法
 UILongPressGestureRecognizer * longTap =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick:)];
    [self.view addGestureRecognizer:longTap];

-(void)imglongTapClick:(UILongPressGestureRecognizer *)gestrue{
    if (gestrue.state != UIGestureRecognizerStateBegan)
    {
        //这个if一定要加,因为长按会有好几种状态,按住command键,点击UIGestureRecognizerStateBegan就能看到所有状态的枚举了,因为如果不加这句的话,此方法可能会被执行多次
        return;//什么操作都不做,直接跳出此方法
    }
    //此处执行你想要执行的代码
//    UIImage *image = [[UIImage alloc] init];/*当然此处需要拿到你需要保存的图片*/
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //保存到图片库里面
    UIImage *image = [self snapshot:window/*你要截取的视图*/];
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
//保存的指定的目录里面
//    NSString * path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"蛋壳公众号.jpg"];
//    [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
}
//把view转成image
- (UIImage *)snapshot:(UIView *)view
{
    //保存全屏
//    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
//    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
//    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    //保存局部截图
    CGRect rect =self.view.frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGRect rect1 = CGRectMake(68 * KX , 140 * KY , 240 * KX , 240 * KY);
    UIImage * image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([img CGImage], rect1)];
    return image;
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *message = @"保存失败";
    if (!error) {
        message = @"成功保存到相册";
    }else
    {
        message = [error description];
    }
    NSLog(@"message is %@",message);

}

你可能感兴趣的:(ios 长按截图)