之前在使用MWPhotoBrowser展示图片时并没有卡顿现象,上次版本更新时添加了图片的保存功能之后,滑动展示图片时就变得又卡又顿(特别是在弱网时),就重新梳理一番,发现了卡顿的原因。
/*
这个方法又重新优化一下,将图片转成NSData保存下来会耗时,会导致滑动查看图片时卡顿,方法之一就是开一个线程,执行耗时操作。还有一个方法,就是直接找到当前图片的index,通过index获取到要保存的图片,这个方法是朋友想到的,在此写出来,大家可以看一下,非常管用
*/
//获取当前点击的图片
-(void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// 执行耗时的异步操作...
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_tempImgArr[index][@"original"]]]]];
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主线程,执行UI操作
_saveImg = img;
}); });
}
//方法二:直接上代码,大家一看就明白了
//在 MWPhotoBrowser.h 中添加方法
- (UIImage *)getCurrentImageWithIndex:(NSInteger)index;
//在 MWPhotoBrowser.m 中实现
- (UIImage *)getCurrentImageWithIndex:(NSInteger)index {
MWPhoto *photo = [self photoAtIndex:index];
return [self imageForPhoto:photo];
}
//在使用的地方进行调用
-(void)longPressCircleAction:(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([_photoBrowser getCurrentImageWithIndex:_photoBrowser.currentIndex], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
// 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];
}
}
这只是对之前写的方法进行修改,看全部方法可以找之前的文章,有不足之处,请留言,谢谢!