緩衝圖片 — 或者不緩衝 imageWithContentsOfFile imageNamed

來源:互聯網
上載者:User

緩衝圖片
— 或者不緩衝

iOS中從程式bundle中載入UIImage一般有兩種方法。第一種比較常見:imageNamed。第二種方法很少使用:imageWithContentsOfFile

為什麼有兩種方法完成同樣的事情呢?

imageNamed的優點在於可以緩衝已經載入的圖片。蘋果的文檔中有如下說法:

This
method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns
the resulting object.

 這種方法會在系統緩衝中根據指定的名字尋找圖片,如果找到了就返回。如果沒有在緩衝中找到圖片,該方法會從指定的檔案中載入圖片資料,並將其緩衝起來,然後再把結果返回。

而imageWithContentsOfFile方法只是簡單的載入圖片,並不會將圖片緩衝起來。

這兩個方法的使用方法如下:

  1. UIImage *img = [UIImage imageNamed:@"myImage"]; // caching
  2. // or
  3. UIImage *img = [UIImage imageWithContentsOfFile:@"myImage"]; // no caching

那麼該如何選擇呢?

如果載入一張很大的圖片,並且只使用一次,那麼就不需要緩衝這個圖片。這種情況imageWithContentsOfFile比較合適——系統不會浪費記憶體來緩衝圖片。

然而,如果在程式中經常需要重用的圖片,那麼最好是選擇imageNamed方法。這種方法可以節省出每次都從磁碟載入圖片的時間。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.