zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS开发 - 保存图片到相册和保存屏幕截图到相册

ios开发 图片 保存 屏幕 截图 相册
2023-09-11 14:21:22 时间

恰巧想起来截图于是就去翻了老代码,也和网上的方法做了验证,千篇一律吧,做个整理和总结

1.保存图片到相册:

//这里的图片可以是本地图片也可以是网络的图片,网络的需要通过SD转化   
UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{

    if (error == nil) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];

    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }

}

2.保存屏幕截图

这是一个含block的方法,使用时可以通过这个方法拿到保存屏幕截图成功失败后的回调,进而做出某些操作。此处的selector方法和上面的一样,也是上一个方法的延伸,设置保存的区域大小
/**
 *  简单截屏并将图片保存到本地
 */
-(void)makeScreenShotCompletion:(void(^)(UIImage * image))completion{
    //开启上下文  <span style="font-family: Arial, Helvetica, sans-serif;">设置截屏大小</span>
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    //获取图片
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    //关闭上下文
    UIGraphicsEndImageContext();
    completion(image);

    /**
     *  将图片保存到本地相册
     */
    UIImageWriteToSavedPhotosAlbum(image, self , @selector(image:didFinishSavingWithError:contextInfo:), nil);//保存图片到照片库

}

最后附Demo下载地址:点击下载