- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/*
保存图片有两种方式:
1>.按钮方式;
2>.长按图片方式;
*/
//显示图片
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
//[注意??] : "9.jpg" 这里是图片名的名字,用户更改成相应的图片名
_imageV.image = [UIImage imageNamed:@"9.jpg"];
//使用手势必须开启交互性
_imageV.userInteractionEnabled = YES;
[self.view addSubview:_imageV];
//方式一 : 给图片添加长按手势
UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector
(longPressClick:)];
//设置长按时间,默认0.5秒
longPress.minimumPressDuration = 1.0;
[self.imageV addGestureRecognizer:longPress];
//方式二 : 创建按钮
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.backgroundColor = [UIColor yellowColor];
[btn setTitle:@"保存相册" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
btn.frame =CGRectMake(30, 70, 100, 30);
[self.view addSubview:btn];
[btn addTarget:self action:@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);
}
}