萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 按鈕點擊異步載入圖片:3 種實現方案對比

場景:按鈕點擊 → 異步下載圖片 → 設為按鈕圖示

常見於用戶頭像編輯、商品圖片選擇、分享縮圖生成等場景。核心要求:**不阻塞主執行緒、支援取消、記憶體安全、完成回調**。

方案一:自定義 AsyncImageView(傳統 NSURLConnection 版)

架構:UIView 子類,內部管理 NSURLConnection、NSMutableData。
缺點:NSURLConnection 已棄用 (iOS 9+)、手動記憶體管理易漏、無快取、無取消併發控制。


// 核心邏輯摘要(完整代碼見原文)
@interface AsyncImageView : UIView
- (void)loadImageFromURL:(NSURL *)url;
@end

@implementation AsyncImageView {
    NSURLConnection *connection;
    NSMutableData *receivedData;
}

- (void)loadImageFromURL:(NSURL *)url {
    [connection cancel]; connection = nil;
    [receivedData release]; receivedData = nil;
    
    NSURLRequest *req = [NSURLRequest requestWithURL:url 
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                     timeoutInterval:60];
    connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    if (!receivedData) receivedData = [[NSMutableData alloc] initWithCapacity:2048];
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    [connection release]; connection = nil;
    UIImage *img = [UIImage imageWithData:receivedData];
    [receivedData release]; receivedData = nil;
    
    // 移除舊圖、加入新圖
    for (UIView *v in self.subviews) [v removeFromSuperview];
    UIImageView *iv = [[UIImageView alloc] initWithImage:img];
    iv.contentMode = UIViewContentModeScaleAspectFit;
    iv.frame = self.bounds;
    [self addSubview:iv];
}

- (void)dealloc {
    [connection cancel];
    [connection release];
    [receivedData release];
    [super dealloc];
}
@end

方案二:UIButton 分類 + GCD 異步下載(現代化、輕量)

優點:無第三方依賴、GCD 佇列控制、支援縮放、Logo 疊加、完成回調。
適用:輕量專案、不想引入大型框架。


// UIButton+AsyncImage.h
@interface UIButton (AsyncImage)
- (void)setImageFromURL:(NSString *)urlString 
           adjustToSize:(CGSize)size 
            completion:(void (^)(void))completion 
                   logo:(UIImage *)logoImage;
@end

// UIButton+AsyncImage.m
@implementation UIButton (AsyncImage)

- (void)setImageFromURL:(NSString *)urlString 
           adjustToSize:(CGSize)size 
            completion:(void (^)(void))completion 
                   logo:(UIImage *)logoImage {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:urlString];
        NSData *data = [NSData dataWithContentsOfURL:url]; // 同步下載在背景隊列
        UIImage *image = [UIImage imageWithData:data];
        
        if (image) {
            // 縮放適配按鈕尺寸
            if (!CGSizeEqualToSize(size, CGSizeZero)) {
                CGFloat scale = [self scaleImage:image adjustToSize:size];
                image = [UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
            }
            
            // 疊加 Logo
            if (logoImage) {
                image = [self addLogoImage:logoImage toImage:image];
            }
            
            // 回主執行緒更新 UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setImage:image forState:UIControlStateNormal];
                if (completion) completion();
            });
        } else {
            NSLog(@"異步載入失敗: %@", urlString);
        }
    });
}

// 縮放比例計算
- (CGFloat)scaleImage:(UIImage *)image adjustToSize:(CGSize)size {
    CGFloat xScale = size.width / image.size.width;
    CGFloat yScale = size.height / image.size.height;
    return 1.0 / MIN(xScale, yScale);
}

// Logo 疊加(右上角)
- (UIImage *)addLogoImage:(UIImage *)logo toImage:(UIImage *)base {
    CGFloat scale = [UIScreen mainScreen].scale;
    int w = scale * base.size.width;
    int h = scale * base.size.height;
    int lw = logo.scale * logo.size.width;
    int lh = logo.scale * logo.size.height;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(NULL, w, h, 8, 4*w, cs, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), base.CGImage);
    CGContextDrawImage(ctx, CGRectMake(w-lw, 0, lw, lh), logo.CGImage);
    CGImageRef result = CGBitmapContextCreateImage(ctx);
    CGContextRelease(ctx);
    CGColorSpaceRelease(cs);
    
    return [UIImage imageWithCGImage:result scale:scale orientation:base.imageOrientation];
}

@end

方案三:專業圖片管理器架構(SDWebImage 風格)

適用:中大型專案、列表大量圖片、需要磁碟快取、佔位圖、漸進載入、指標圖、預載入。


// ImageManager.h
@interface ImageManager : NSObject
@property (nonatomic, strong) NSMutableDictionary *memoryCache;
@property (nonatomic, assign) dispatch_queue_t networkQueue;

+ (instancetype)sharedInstance;

// 核心異步載入
- (void)asyncLoadImageWithURL:(NSString *)urlString 
                   imageView:(UIImageView *)imageView 
              placeholder:(UIImage *)placeholder
                 completion:(void (^)(UIImage *image, NSError *error))completion;

// 進階:插隊載入(優先顯示)、清理舊任務
- (void)asyncLoadImageWithURL:(NSString *)urlString 
                   imageView:(UIImageView *)imageView 
              placeholder:(UIImage *)placeholder
                 priority:(BOOL)highPriority
                cleanOld:(BOOL)cleanOld
                 completion:(void (^)(UIImage *, NSError *))completion;
@end

實現要點:

  • 記憶體快取:`NSCache`,`countLimit` + `totalCostLimit`
  • 磁碟快取:`NSFileManager` 寫入 Caches 目錄,檔名用 URL MD5
  • 任務去重:同一 URL 進行中任務合併回調
  • Cell 複用取消:`prepareForReuse` 中 `cancel` 對應任務
  • 圖片解碼:背景執行緒 `CGImageSourceCreateThumbnailAtIndex` 預解碼,避免主執行緒卡頓

方案對比與選型建議

維度方案一 AsyncImageView方案二 UIButton 分類方案三 ImageManager
複雜度低中高
異步下載NSURLConnection (棄用)GCD + 同步下載NSURLSession + 任務管理
快取無無記憶體 + 磁碟雙層
取消/去重無無完整支援
進階功能無縮放、Logo疊加佔位、漸進、指標、預載
推薦場景教學、極簡原型輕量專案、按鈕圖片生產環境、列表、複雜需求

生產環境強烈建議:直接用成熟框架

  • SDWebImage (ObjC 經典、功能最全、社區最大)
  • Kingfisher (Swift 純粹、API 現代、效能優)
  • Nuke (Swift、支援 SwiftUI/Combine、架構最先進)
  • AlamofireImage (Alamofine 生態、輕量)

自建僅適合學習或極特殊定製需求,維護成本極高。

copyright © 萬盛學電腦網 all rights reserved