2013-03-29 46 views
3

我使用下面的代码在我的ImageView显示图像显示它比较快的方式:从URL中加载图像,并在iPhone应用程序

imgbackBG.image = [UIImage imageWithData: 
        [NSData dataWithContentsOfURL: 
        [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", [test.arrImagessplash objectAtIndex:[test.arrImages count]-4]]]]]; 

    4cing.com/mobile_app/uploads/pageicon/splash.png 

的问题是,代码执行速度非常缓慢。有没有办法加载图像并更快地将其显示在ImageView中?如果是这样,我该怎么做?

+1

使用Asychnrous图像加载方法猪头...一旦有一个在他们过目..... –

+0

可以请给一些示例代码? – Anjaneyulu

+0

看了这个,并熟悉这个用法然后看看SDWebImage ...享受 –

回答

3

和下载文件从这里.....

https://github.com/nicklockwood/AsyncImageView

和下列方式使用:

AsyncImageView *asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(30,32,100, 100)]; 
[asyncImageView loadImageFromURL:[NSURL URLWithString:your url]]; 
[YourImageView addSubview:asyncImageView]; 
[asyncImageView release]; 
+0

谢谢你@manohar .. – Anjaneyulu

+0

我得到的代码的第二行loadImageFromURL方法调用的错误是否有任何解决方案 –

18

您正在使用的代码在主线程中加载图像。这将阻止用户界面。使用GCD异步加载图像。

下面是示例代码:

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
     dispatch_async(q, ^{ 
      /* Fetch the image from the server... */ 
      NSData *data = [NSData dataWithContentsOfURL:url]; 
      UIImage *img = [[UIImage alloc] initWithData:data]; 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       /* This is the main thread again, where we set the tableView's image to 
       be what we just fetched. */ 
       cell.imgview.image = img; 
      }); 
     }); 
+0

感谢你@Ramu Pasupuleti ..可以解释wt hapen当上面的代码执行在我的程序? – Anjaneyulu

+0

@anjaneyulu reddy pokala,从url获取图像可能需要一些时间,所以通过使用GCD异步它将在单独的线程上运行。所以,试试看,并有很多链接:http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial和官方参考链接是:https: //developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html。您可以了解更多 –

+0

上面的代码还可以加载时间来加载该图像? – Anjaneyulu

1
Best way to used `NSOperationQueue` to load Image in background. 
Here is the sample code: 


    NSOperationQueue *myQueue = [[NSOperationQueue alloc] init]; 
    [myQueue addOperationWithBlock:^{ 
     UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@""]]]?:[UIImage imageNamed:@"defaultImage.png"]; 
     [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
      YourImageView.image = img; 

     }]; 
    }]; 
相关问题