您的位置:首页 > 移动开发 > IOS开发

iOS--使用MWPhotoBrowser进行图片保存

2017-10-09 00:00 891 查看
多的话不说,直接上代码:

遵守MWPhotoBrowserDelegate协议,

NSMutableArray *_tempImgArr;//存储图片的数据源

UIImage *_saveImg; //将要保存的图片

//点击图片 放大
-(void)imgClick:(NSInteger)index
{
//创建MWPhotoBrowser ,要使用initWithDelegate方法,要遵循MWPhotoBrowserDelegate协议
MWPhotoBrowser *browser = [[MWPhotoBrowser alloc]initWithDelegate:self];
//设置当前要显示的图片
[browser setCurrentPhotoIndex:index];
//显示导航条(根据自己需求)
self.navigationController.navigationBar.hidden = NO;
browser.navigationController.navigationBar.hidden = NO;
//push到MWPhotoBrowser
[self.navigationController pushViewController:browser animated:YES];
}

//图片的个数
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{

return _tempImgArr.count;
}
//通过下标获取图片
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{

//创建图片模型
MWPhoto *ph = [MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_tempImgArr[index][@"original"]]]];
//图片添加长按手势
UILongPressGestureRecognizer *lpGes = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
[photoBrowser.view addGestureRecognizer:lpGes];

return ph;

}
//获取当前点击的图片
-(void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
{
_saveImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_tempImgArr[index][@"original"]]]]];
}

//长按手势
-(void)longPressAction:(UILongPressGestureRecognizer *)ges{
//    MWPhotoBrowser *photoBrowser = (MWPhotoBrowser*)[Utils getSuperControllerWith:ges.view];
//只在begin执行一次
if (ges.state == UIGestureRecognizerStateBegan) {
NSLog(@"long pressTap state :begin");
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"保存图片到手机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

UIImageWriteToSavedPhotosAlbum(_saveImg, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alertC addAction:action1];
[alertC addAction:action2];
[self.navigationController presentViewController:alertC animated:YES completion:nil];
}

}
// 保存图片后到相册后,回调的相关方法,查看是否保存成功
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:app.window animated:YES];
//显示文字
hud.mode = MBProgressHUDModeText;
if (error == nil){
hud.labelText = @"已保存到手机相册!";

} else {
hud.labelText = @"保存失败!";
}
// 隐藏时候从父控件中移除
hud.removeFromSuperViewOnHide = YES;
[hud hide:YES afterDelay:1.5];
}

如图:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios MWPhotoBrowser