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);

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容