2

我的 UICollectionView 有一点流程问题。我想像在 Apple 的 iBook 应用程序中一样显示 PDF 的缩略图,当我滚动我的收藏视图时,我可以看到它不是很流畅。这是我用来加载图片的方式:

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:    (NSIndexPath *)indexPath
{
     GridCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"gridCell" forIndexPath:indexPath];

    ...

    // Set Thumbnail
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([Tools checkIfLocalFileExist:cell.pdfDoc])
        {
            UIImage *thumbnail = [Tools generateThumbnailForFile:((PDFDocument *)[self.pdfList objectAtIndex:indexPath.row]).title];

            dispatch_async( dispatch_get_main_queue(), ^{
                [cell.imageView setImage:thumbnail];
            });
        }
    });

    ...

    return cell;
}

获取缩略图的方法:

+ (UIImage *)generateThumbnailForFile:(NSString *) fileName
{
    // ----- Check if thumbnail already exist
    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString* thumbnailAddress = [documentsPath stringByAppendingPathComponent:[[fileName stringByDeletingPathExtension] stringByAppendingString:@".png"]];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thumbnailAddress];

    if (fileExists)
        return [UIImage imageWithContentsOfFile:thumbnailAddress];

    // ----- Generate Thumbnail
    NSString* filePath = [documentsPath stringByAppendingPathComponent:fileName];

    CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath];
    CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL(url);
    CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1);
    CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);

    UIGraphicsBeginImageContext(pageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, CGRectGetMinX(pageRect),CGRectGetMaxY(pageRect));
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, -(pageRect.origin.x), -(pageRect.origin.y));
    CGContextDrawPDFPage(context, pageRef);

    // ----- Save Image
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(finalImage)];
    [imageData writeToFile:thumbnailAddress atomically:YES];
    UIGraphicsEndImageContext();

    return finalImage;    
}

你有什么建议吗?

4

1 回答 1

2

看看https://github.com/rs/SDWebImage。该库非常适合异步图像加载,尤其是方法setImageWithURL:placeholderImage:

您可以调用该方法并使用加载图像或空白 png 设置占位符,一旦加载您尝试检索的图像,它将填充占位符。这应该会大大加快您的应用程序的速度。

于 2013-05-24T13:43:21.153 回答