1

在我的 iPhone 应用程序中,我必须显示缩略图的预览。该预览图像实际上是我们将从远程服务器获取的。在屏幕上加载那个大图像之前,我必须显示预加载视图,但实际上这个预加载视图并没有出现在屏幕上。

我使用的代码是:

zoomview=[[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)];
imageloadview.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
[self.view addSubview:imageloadview];
[activity startAnimating];
[self loadimageview];

这里不是在屏幕上加载缩放视图,而是在执行这个加载视图方法,但我想在从服务器获取大图像之前显示预加载视图。

-(void)loadimageview
{
    imageloader.image=[UIImage imageNamed:@""];

    [self loadimage];
}

-(void)loadimage
{
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:[picfullarray objectAtIndex:0]]];

    if([data length]==0)
    {
        NSLog(@"data");
    } 
    else
    {
        UIImage *image1=[UIImage imageWithData:data];
        imageloader.image=image1;

        [activity stopAnimating];
        [loadlabel1 setText:@""];
    }
}

在从服务器获取大图像之前,如何在 iPhone 屏幕上显示预加载视图?

4

3 回答 3

1

您必须使用NSURLRequest异步加载图像。

使类实现NSURLRequestDelegate协议。在 的函数- (void)connectionDidFinishLoading:(NSURLConnection *)connectionNSURLRequestDelegate,添加加载完成时更新视图的代码。

// You must declare NSMutableData somewhere to write received data in delegate method
// - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
// I assume the instance of NSMutableData is named data

// If you want to load multiple images, it is a bit tricky, but doable.
// I'll post the code if that is what you need.

- (void) connectionDidFinishLoading: (NSURLConnection *) connection {
    // You may want to declare a instance member to store the image (UIImage*), so that you can restore the view if the view is unloaded due to memory warning.
    UIImage* image = [UIImage imageWithData: data];


    data = nil; // Important. You should clean the data, or it will take up space.
    // You may want to check whether image != nil, since the incoming data may not be image
    [self displayImage: image];
}

- (void) displayImage: (UIImage*) aImage {
    imageloader.image = aImage;
    // Depending on how UIImageView is initialized, you may need to call sizeToFit.
    // Or set the frame accordingly

    [activity stopAnimating];
    [loadlabel1 setText: @""];
}
于 2012-05-27T05:13:38.700 回答
0

我建议使用SDWebImage框架。它已经具有异步图像加载功能,并且非常易于使用。

[imageView.image setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

您不必担心弄乱NSURLConnection,维护NSData等。

于 2012-06-09T04:12:15.980 回答
0

还有 AFNetworking 可以轻松做到这一点。

https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking

查看“下载和显示图像”部分。

于 2012-06-09T04:18:17.210 回答