加载缓慢时,ALAsset照片库图像性能得到改善
嗨,我有一个问题,我的scrollView上显示图像。
首先我创build新的UIImageView与资产url:
-(void) findLargeImage:(NSNumber*) arrayIndex { ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) { ALAssetRepresentation *rep; if([myasset defaultRepresentation] == nil) { return; } else { rep = [myasset defaultRepresentation]; } CGImageRef iref = [rep fullResolutionImage]; itemToAdd = [[UIImageView alloc] initWithFrame:CGRectMake([arrayIndex intValue]*320, 0, 320, 320)]; itemToAdd.image = [UIImage imageWithCGImage:iref]; [self.scrollView addSubview:itemToAdd]; }; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) { NSLog(@"Cant get image - %@",[myerror localizedDescription]); }; NSURL *asseturl = [NSURL URLWithString:[self.photoPath objectAtIndex:[arrayIndex intValue] ]]; ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init]; [assetslibrary assetForURL:asseturl resultBlock:resultblock failureBlock:failureblock];
}
其中itemToAdd是一个在界面中定义的UIImageView:
__block UIImageView *itemToAdd;
和scrollView定义为一个属性:
@property (nonatomic, strong) __block UIScrollView *scrollView;
然后在我看来,我会这样做:
- (void) viewWillAppear:(BOOL)animated { self.scrollView.delegate = self; [self findLargeImage:self.actualPhotoIndex]; [self.view addSubview:self.scrollView]; }
但图像不会出现,我应该刷新self.view后添加图像scrollView,还是应该做点别的?
ALAssetsLibrary块将在单独的线程中执行。 所以我build议在主线程中做UI相关的东西。
要做到这一点,使用dispatch_sync(dispatch_get_main_queue()或performSelectorOnMainThread
一些重要说明:
-
使用AlAsset aspectRatioThumbnail而不是FullResolutionImage来获得高性能
例:
CGImageRef iref = [myasset aspectRatioThumbnail]; itemToAdd.image = [UIImage imageWithCGImage:iref];
例:
-(void) findLargeImage:(NSNumber*) arrayIndex { ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) { CGImageRef iref = [myasset aspectRatioThumbnail]; dispatch_sync(dispatch_get_main_queue(), ^{ itemToAdd = [[UIImageView alloc] initWithFrame:CGRectMake([arrayIndex intValue]*320, 0, 320, 320)]; itemToAdd.image = [UIImage imageWithCGImage:iref]; [self.scrollView addSubview:itemToAdd]; });//end block }; ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) { NSLog(@"Cant get image - %@",[myerror localizedDescription]); }; NSURL *asseturl = [NSURL URLWithString:[self.photoPath objectAtIndex:[arrayIndex intValue] ]]; ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init]; [assetslibrary assetForURL:asseturl resultBlock:resultblock failureBlock:failureblock]; }
还要改变viewWillAppear()的顺序
- (void) viewWillAppear:(BOOL)animated { self.scrollView.delegate = self; [self.view addSubview:self.scrollView]; [self findLargeImage:self.actualPhotoIndex]; }
您正在操作来自另一个线程的视图。 您必须使用主线程来操作视图。
添加图像到scrollView使用:
dispatch_async(dispatch_get_main_queue(), ^{ [self.scrollView addSubview:itemToAdd]; }
或使用:
[self.scrollView performSelectorOnMainThread:@selector(addSubview:) withObject:itemToAdd waitUntilDone:NO];
请参阅:
- NSObject类参考
- GCD