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

时间:2013-04-09 05:01:49

标签: ios grand-central-dispatch uicollectionview

当我拍照时,我将图像文件保存到我在NSDocuments目录中创建的文件夹中。 (/文档/图片/ .... PNG)

然后我将所有照片加载到集合视图中的照片文件夹中。由于文件很大,我决定使用Grand Central调度来在后台线程上执行抓取图像。但是当我向上和向下滚动UICollectionView时,我可以看到图像在显示正确的图像之前随机变化。我假设每当我抓住图像时我只是在主线程上设置它,但我真的不知道如何处理它。

     - (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;

}

1 个答案:

答案 0 :(得分:0)

查看Apple的示例应用程序:LazyTableImages。我刚将它成功地整合到一个集合视图中。

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