将图像加载到ScrollView

时间:2011-06-13 08:54:06

标签: iphone scrollview

你有一个问题,在磁盘上缓存到UIScrollView的加载映像(1024x1024)需要一段时间(只是一个lagg但是annoing)加载到内存中。 当使用尺寸为668px×445px的图像时,lagg是可以接受的。 当我使用dispatch_async

时,我尝试使用相同结果的线程加载数据

如何提高加载数据异步的性能?

-(void)setupImageView:(BMPhoto *)_photo {
    methodStart = [[NSDate date] retain];

    if ([[photo imageUrl] isEqualToString:[_photo imageUrl]])
        return;

     photo = _photo;

    [imageView removeFromSuperview];
    [imageView release];
    imageView = nil;

    self.zoomScale = 1.0;
    BMCache *cache = [BMCache sharedCache];


    if ([cache isFileCached:[photo imageUrl]]) {
        [NSThread detachNewThreadSelector:@selector(loadImageFromCache:) toTarget:self withObject:[photo imageUrl]];
    } else {
        [NSThread detachNewThreadSelector:@selector(loadImageFrom:) toTarget:self withObject:[photo imageUrl]];
    }
}
-(void)loadImageFromCache:(NSString *)url{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    UIImage *image = [UIImage imageWithData:[[BMCache sharedCache] getCachedRemoteFile:url]];
    [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
   [pool release];
}
-(void)loadImageFrom:(NSString *)url{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[photo imageUrl]]];
    [[BMCache sharedCache] addRemoteFileToCache:url withData:imageData];

    UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
    [imageData release];
    [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
    [pool release];
}

- (void)displayImage:(UIImage *)image {
    NSDate *methodFinish1 = [NSDate date];
    NSTimeInterval executionTime1 = [methodFinish1 timeIntervalSinceDate:methodStart];
    NSLog(@"Thread Done time: %f", executionTime1);

    if (image) {
        //imageView.image = nil;
        imageView = [[BMPhotoViewImageView alloc] initWithImage:image];
        [self addSubview:imageView];

        self.contentSize = [image size];
        [self setMaxMinZoomScalesForCurrentBounds];
        self.zoomScale = self.minimumZoomScale;
        NSTimeInterval executionTime2 = [[NSDate date] timeIntervalSinceDate:methodFinish1];
        NSLog(@"Load image time time: %f", executionTime2);

        NSDate *methodFinish = [NSDate date];
        NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
        NSLog(@"Total time: %f", executionTime);
        NSLog(@"-------------------------------------------");
    }
}

线程完成时间:0.015229 加载图像时间:0.009824

总时间:0.028263

线程完成时间:0.025037 加载图像时间:0.005314

总时间:0.035781

线程完成时间:0.026063 加载图像时间:0.004379

总时间:0.033177

1 个答案:

答案 0 :(得分:0)

您可以尝试...首先显示imageView(方法displayImage)放置一些小图像状态“加载”或活动指示器。然后加载(使用线程)并将实际图像设置为imageView。