您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 等比例壓縮與裁切圖片

編輯:iOS 相關資訊

若要把圖片先等比縮放,再裁切成指定尺寸,可先建立目標尺寸的圖形上下文,再依原圖與目標比例決定繪製區域。

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

    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth / heightScale, height)];
    } else {
        [image drawInRect:CGRectMake(0, 0, width, imageHeight / widthScale)];
    }
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

這個做法會讓圖片填滿目標區域,再視情況裁掉多餘部分。若需要置中裁切,可再調整 drawInRect 的 x、y 偏移。

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