简体   繁体   English

使用GCD将图像从文件加载到UICollectionView

[英]Loading images from file to UICollectionView, using GCD

When i take a picture, I save the image file in to a folder i made in the NSDocuments Directory. 拍照时,将图像文件保存到我在NSDocuments目录中创建的文件夹中。 (/Documents/Photos/....png) (/Documents/Photos/....png)

Then I load all the photos in the photo's folder in the collection view. 然后,我将所有照片加载到收藏夹视图中的照片文件夹中。 Since the files are big, I decided to use Grand Central dispatch to perform grabbing the image on the background thread. 由于文件很大,因此我决定使用Grand Central分派来在后台线程上捕获图像。 But when i scroll up and down the UICollectionView i can see images changing randomly before displaying the correct image. 但是当我上下滚动UICollectionView时,我可以看到图像在显示正确的图像之前随机变化。 I assume that whenever i grab the image I just set it on the main thread, but I really don't know how to deal with this. 我以为只要获取图像,我就将其设置在主线程上,但是我真的不知道该如何处理。

     - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    NSUInteger rowNumber = [indexPath row];

    //NSString *imagePath = [self.photoPathArray objectAtIndex:rowNumber];

    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"Photos"] error:NULL];

    NSString *imagePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/Photos/%@",[directoryContent objectAtIndex:rowNumber]];

    NSLog(@"the image path is %@", imagePath);

        imageCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

         UIImage *originalImage = [UIImage imageWithContentsOfFile:imagePath];
         UIImage *thumbNail = [self shrinkImage:originalImage withSize:CGSizeMake(200, 200)];


         dispatch_sync(dispatch_get_main_queue(), ^{
             cell.imageView.image = thumbNail;
         });

     });

    return cell;

}

Check out Apple's sample app: LazyTableImages. 查看Apple的示例应用程序:LazyTableImages。 I just incorporated it successfully into a collection view. 我刚刚将它成功地合并到集合视图中。

http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM