SDWebImage的簡單使用,sdwebimage使用

來源:互聯網
上載者:User

SDWebImage的簡單使用,sdwebimage使用

一、前言

  第一次使用SDWebImage是在自己做《康複醫生》的時候。記得那時有一個表格要顯示所有的帳戶圖片。不使用它的時候每次載入該table都會很卡頓,後來使用後發現不卡頓了。瞬間感覺這個世界好有愛。

二、安裝

  首先,SDWebImage的git地址是:https://github.com/rs/SDWebImage。我們可以直接到這裡進行下載,然後添加到自己的項目中去。

三、使用情境(前提是已經匯入了SDWebImage這個庫)

1、情境一、載入圖片

    使用SDWebImage可以去載入遠程圖片,而且還會緩衝圖片,下次請求會看一下是否已經存在於緩衝中,如果是的話直接取本機快取,如果不是的話則重新請求。使用方法很簡單,在需要使用該情境的類中匯入

#import "UIImageView+WebCache.h"

然後調用:

- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

即可。

  我們還可以在UIImageView+WebCache.h中看到其他的方法,和上邊的方法類似,讀者自行查看即可。

2、情境二、使用它做本機快取

  很多時候我們可能拍照得到的一張圖片要多個地方使用,那麼我們就希望可以把這張圖片放到緩衝裡面,然後每次用這張圖片的時候就去通過特定的方式取即可。SDWebImage就有這樣的一個類:SDImageCache。該類完美地協助了我們解決了這個問題。

  使用的時候,我們首先要在使用的類裡面做匯入:

#import "SDImageCache.h"

然後就可以進行相關的操作了。讓我們直接看看SDImageCache.h檔案:

@property (assign, nonatomic) NSUInteger maxMemoryCost;/** * The maximum length of time to keep an image in the cache, in seconds */@property (assign, nonatomic) NSInteger maxCacheAge;/** * The maximum size of the cache, in bytes. */@property (assign, nonatomic) NSUInteger maxCacheSize;/** * Returns global shared cache instance * * @return SDImageCache global instance */+ (SDImageCache *)sharedImageCache;/** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */- (id)initWithNamespace:(NSString *)ns;/** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */- (void)addReadOnlyCachePath:(NSString *)path;/** * Store an image into memory and disk cache at the given key. * * @param image The image to store * @param key   The unique image cache key, usually it's image absolute URL */- (void)storeImage:(UIImage *)image forKey:(NSString *)key;/** * Store an image into memory and optionally disk cache at the given key. * * @param image  The image to store * @param key    The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;/** * Store an image into memory and optionally disk cache at the given key. * * @param image       The image to store * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage * @param imageData   The image data as returned by the server, this representation will be used for disk storage *                    instead of converting the given image object into a storable/compressed image format in order *                    to save quality and CPU * @param key         The unique image cache key, usually it's image absolute URL * @param toDisk      Store the image to disk cache if YES */- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;/** * Query the disk cache asynchronously. * * @param key The unique key used to store the wanted image */- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;/** * Query the memory cache synchronously. * * @param key The unique key used to store the wanted image */- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;/** * Query the disk cache synchronously after checking the memory cache. * * @param key The unique key used to store the wanted image */- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;/** * Remove the image from memory and disk cache synchronously * * @param key The unique image cache key */- (void)removeImageForKey:(NSString *)key;/** * Remove the image from memory and disk cache synchronously * * @param key             The unique image cache key * @param completionBlock An block that should be executed after the image has been removed (optional) */- (void)removeImageForKey:(NSString *)key withCompletition:(void (^)())completion;/** * Remove the image from memory and optionally disk cache synchronously * * @param key      The unique image cache key * @param fromDisk Also remove cache entry from disk if YES */- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;/** * Remove the image from memory and optionally disk cache synchronously * * @param key             The unique image cache key * @param fromDisk        Also remove cache entry from disk if YES * @param completionBlock An block that should be executed after the image has been removed (optional) */- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletition:(void (^)())completion;/** * Clear all memory cached images */- (void)clearMemory;/** * Clear all disk cached images. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */- (void)clearDiskOnCompletion:(void (^)())completion;/** * Clear all disk cached images * @see clearDiskOnCompletion: */- (void)clearDisk;/** * Remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock;/** * Remove all expired cached image from disk * @see cleanDiskWithCompletionBlock: */- (void)cleanDisk;/** * Get the size used by the disk cache */- (NSUInteger)getSize;/** * Get the number of images in the disk cache */- (NSUInteger)getDiskCount;/** * Asynchronously calculate the disk cache's size. */- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock;/** * Check if image exists in cache already */- (BOOL)diskImageExistsWithKey:(NSString *)key;/** *  Get the cache path for a certain key (needs the cache path root folder) * *  @param key  the key (can be obtained from url using cacheKeyForURL) *  @param path the cach path root folder * *  @return the cache path */- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;/** *  Get the default cache path for a certain key * *  @param key the key (can be obtained from url using cacheKeyForURL) * *  @return the default cache path */- (NSString *)defaultCachePathForKey:(NSString *)key;

  不要看著想吐就行。先看看使用吧。

 存圖片:

 SDImageCache *imageCache = [SDImageCache sharedImageCache];

   [imageCache storeImage:image forKey:@"myphoto" toDisk:YES];

取圖片:

 SDImageCache *imageCache = [SDImageCache sharedImageCache];    UIImage *image = [imageCache imageFromDiskCacheForKey:@"myphoto"];

這樣就可以取到自己存的圖片了。可以看一下SDImageCache.h這個類了,裡面提供了存圖片到記憶體和磁碟的方法,還有取圖片的方法,以及判斷該圖片是否存在的方法。還有就是刪除圖片、清空磁碟緩衝、得到緩衝大小等方法。

情境三、做設定中的清除緩衝功能

  簡單來說,當我們點擊清除緩衝按鈕的時候會觸發的訊息如下:

- (void)clearCaches{    [MBProgressHUD showMessage:@"正在清理.."];        [[SDImageCache sharedImageCache] clearMemory];    [[SDImageCache sharedImageCache] clearDisk];    [self performSelectorOnMainThread:@selector(cleanCacheSuccess) withObject:nil waitUntilDone:YES];}

- (void)cleanCacheSuccess


{


    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{



        self.cacheLab.text = @"0.00M";


        return;

   });


}

很簡單,就是把使用SDWebImage緩衝的圖片都清空就可以了,這裡包括了記憶體中的緩衝圖片以及磁碟上的緩衝圖片。

 

還有其他的使用情境,這裡就不再贅述了。

四、實現原理

  其實SDWebImage之所以能夠實現緩衝的原理關鍵就是在哪個key值。

  比如我們在使用

- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

的時候,其實就是把url當做了一個圖片的key值,然後儲存對應的圖片,如果下次請求的url和這次請求的url一樣,那麼就直接根據url(這個key)來取圖片,如果url作為key的圖片緩衝不存在,就去請求遠程伺服器,然後請求過來之後再次將url和圖片對應,然後儲存。

五、其他

  未完待續。

相關文章

聯繫我們

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