ios UIImageView非同步載入網狀圖片

來源:互聯網
上載者:User

標籤:沒有   uiimage   init   載入   png   ges   oca   sub   ring   

方法1:在UI線程中同步載入網狀圖片

  1. UIImageView *headview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];  
  2.   
  3. NSURL *photourl = [NSURL URLWithString:@"http://www.exampleforphoto.com/pabb/test32.png"];  
  4. //url請求實在UI主線程中進行的  
  5. UIImage *images = [UIImage imageWithData:[NSData dataWithContentsOfURL:photourl]];//通過網路url擷取uiimage  
  6. headview.image = images;  

這是最簡單的,但是由於在主線程中載入,會阻塞UI主線程。所以可以試試NSOperationQueue,一個NSOperationQueue 操作隊列,就相當於一個線程管理器,而非一個線程。因為你可以設定這個線程管理器內可以並行啟動並執行的線程數量等等。

 

方法2:使用NSOperationQueue非同步載入

  1. 下面就是使用NSOperationQueue實現子線程載入圖片:  
  2. - (void)viewDidLoad  
  3. {  
  4.     [super viewDidLoad];  
  5.       
  6.     NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];  
  7.       
  8.     self.imageview  = [[[UIImageView alloc] initWithFrame:CGRectMake(110, 50, 100, 100)] autorelease];  
  9.     [self.imageview setBackgroundColor:[UIColor grayColor]];  
  10.     [self.view addSubview:self.imageview];  
  11.       
  12.     NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];  
  13.     [operationQueue addOperation:op];  
  14. }  
  15.   
  16. - (void)downloadImage  
  17. {  
  18.     NSURL *imageUrl = [NSURL URLWithString:HEADIMAGE_URL];  
  19.     UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];  
  20.     self.imageview.image = image;  
  21. }  

不過這這樣的設計,雖然是非同步載入,但是沒有緩衝圖片。重新載入時又要重新從網路讀取圖片,重複請求,實在不科學,所以可以考慮第一次請求時儲存圖片。

 

ios UIImageView非同步載入網狀圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.