美文网首页互联网科技iOS DeveloperiOS开发
iOS开发中,如何将图片保存到相册

iOS开发中,如何将图片保存到相册

作者: KennyHito | 来源:发表于2016-06-25 23:01 被阅读767次

    - (void)viewDidLoad {

    [superviewDidLoad];

    self.view.backgroundColor= [UIColorwhiteColor];

    /*

    保存图片有两种方式:

    1>.按钮方式;

    2>.长按图片方式;

    */

    //显示图片

    _imageV= [[UIImageViewalloc]initWithFrame:CGRectMake(100,100,200,200)];

    //[注意🐷] : "9.jpg"这里是图片名的名字,用户更改成相应的图片名

    _imageV.image= [UIImageimageNamed:@"9.jpg"];

    //使用手势必须开启交互性

    _imageV.userInteractionEnabled=YES;

    [self.viewaddSubview:_imageV];

    //方式一:给图片添加长按手势

    UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(longPressClick:)];

    //设置长按时间,默认0.5秒

    longPress.minimumPressDuration=1.0;

    [self.imageVaddGestureRecognizer:longPress];

    //方式二:创建按钮

    UIButton* btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

    btn.backgroundColor= [UIColoryellowColor];

    [btnsetTitle:@"保存相册"forState:UIControlStateNormal];

    [btnsetTitleColor:[UIColororangeColor]forState:UIControlStateNormal];

    btn.frame=CGRectMake(30,70,100,30);

    [self.viewaddSubview:btn];

    [btnaddTarget:selfaction:@selector(btnClick:)forControlEvents:UIControlEventTouchUpInside];

    }

    //长按手势实现图片保存

    - (void)longPressClick:(UIGestureRecognizer*)longPress{

    //必须加上判断语句防止多次保存

    if(longPress.state==UIGestureRecognizerStateBegan) {

    UIImageWriteToSavedPhotosAlbum(self.imageV.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);

    }

    }

    //按钮点击事件的实现

    - (void)btnClick:(UIButton*)btn{

    UIImageWriteToSavedPhotosAlbum(self.imageV.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);

    }

    //保存图片的方法

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

    if(!error) {

    NSLog(@"成功图片保存到相册");

    }else{

    NSLog(@"%@",error.localizedDescription);

    }

    }

    工程下载地址:  github.com/NSLog-YuHaitao/savePhoto.git

    相关文章

      网友评论

        本文标题:iOS开发中,如何将图片保存到相册

        本文链接:https://www.haomeiwen.com/subject/bnpadttx.html