您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 圖片等比縮放與裁切:一段 UIGraphics 的實作

編輯:iOS 技巧大全

需求是這樣的:把一張圖片按需要的尺寸等比縮放,然後裁切出目標區域。也就是說不讓圖片變形,而是以「填滿目標矩形」為前提縮放,再取中央(或指定位置)的部分。

+ (UIImage *)compressImageWith:(UIImage *)image width:(float)width height:(float)height
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float widthScale = imageWidth / width;
    float heightScale = imageHeight / height;

    // 建立一個 bitmap context,並設為目前的 context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));

    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth / heightScale, height)];
    } else {
        [image drawInRect:CGRectMake(0, 0, width, imageHeight / widthScale)];
    }

    // 從目前 context 取得縮放後的圖片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    // 使目前的 context 出堆疊
    UIGraphicsEndImageContext();

    return newImage;
}

程式碼在做什麼

關鍵是兩個縮放比的比較。widthScale 是「原圖寬度 ÷ 目標寬度」,heightScale 同理。取決於哪個比值較大,決定要裁掉哪一邊:

  • 若 widthScale > heightScale,代表寬度方向的壓縮比例較大,於是依高度比例縮放(imageHeight / heightScale 作為繪製寬度),讓高度剛好填滿,寬度則超出後被 context 裁掉。
  • 否則反之,讓寬度剛好填滿,高度超出後被裁掉。

這就是「aspect fill」的效果:填滿且不變形,代價是部分內容被裁切。若你要的是「aspect fit」(完整顯示、留白),邏輯要改成取較小的比例,並計算置中偏移。

幾個可以改進的地方

用 UIGraphicsImageRenderer 取代舊 API。 UIGraphicsBeginImageContext 系列在 iOS 10 之後已被取代,新寫法更簡潔也更能拿到列印解析度:

+ (UIImage *)compressImageWith:(UIImage *)image width:(CGFloat)width height:(CGFloat)height
{
    UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];
    UIGraphicsImageRenderer *renderer =
        [[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(width, height) format:format];
    return [renderer imageWithActions:^(UIGraphicsImageRendererContext *ctx) {
        // 依 aspect fill 計算繪製矩形
        ...
    }];
}

注意 scale 與解析度。 UIGraphicsBeginImageContext 產生的圖片 scale 固定為 1.0,在 Retina 螢幕上會顯得模糊。若在意清晰度,改用 UIGraphicsBeginImageContextWithOptions(size, YES, 0.0) 讓它依螢幕自動採用正確 scale。

大圖會吃記憶體。 解壓後的 UIImage 在記憶體中佔 width × height × 4 bytes。一張 4000×3000 的相簿原圖約需 48MB,同時處理幾張就可能被系統終止。實務上建議先用 ImageIO 的 CGImageSourceCreateThumbnailAtIndex 直接產生縮圖,避免完整解碼。

別忘了 orientation。 從相簿或相機取得的 UIImage 可能帶有 imageOrientation 中繼資料,直接取 .size 與 CGImage 的尺寸可能不一致,導致旋轉或變形。處理前建議先呼叫 -drawInRect: 前的正規化,或直接用 CGImageSource 一次處理 orientation 與縮放。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved