我试图从图书馆获取照片并在collectionView
中显示。我的collectionView
启用了分页功能。有我的代码,它的工作原理:
- (void)fetchImage:(PHAsset *)asset completion:(void(^)(UIImage *image))completion {
//Fetch image from asset
CGFloat scale = [UIScreen mainScreen].scale;
CGFloat scaleWidth = [UIScreen mainScreen].bounds.size.width * scale;
CGFloat scaleHeight = [UIScreen mainScreen].bounds.size.height * scale;
CGSize retinaSquare = CGSizeMake(scaleWidth, scaleHeight);
representedAssetIdentifier = [NSString stringWithFormat:@"%@", asset.localIdentifier];
PHImageRequestOptions *option = [PHImageRequestOptions new];
option.resizeMode = PHImageRequestOptionsResizeModeFast;
option.synchronous = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset
targetSize:retinaSquare
contentMode:PHImageContentModeAspectFill
options:option
resultHandler:^(UIImage *result, NSDictionary *info) {
// Set the cell's thumbnail image if it's still showing the same asset.
if ([representedAssetIdentifier isEqualToString:asset.localIdentifier]) {
completion(result);
}
}];
}
在cellForItemAtIndexPath
:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PhotosCell *cell = (PhotosCell *)[collectionView dequeueReusableCellWithReuseIdentifier:[self cellIdentifier] forIndexPath:indexPath];
PhotoItemModel *item = _controller.assetModels[indexPath.row];
[_controller fetchImage:item.asset completion:^(UIImage *image) {
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageItem.image = image;
cell.imageItem.clipsToBounds = YES;
cell.imageItem.contentMode = UIViewContentModeScaleAspectFill;
});
}];
return cell;
}
但我有一个问题:当我尝试滚动到下一张照片时,collectionView
并不粗糙。它会延迟一段时间。
我知道问题来自代码option.synchronous = YES;
。当我删除此代码时,collectionView
很顺利。但我得到另一个问题:有时,照片的质量不好。像那样:
真实的形象:
"有时":
我的问题是:如何平滑加载照片并保持照片质量?