上傳頭像、產生縮圖時常需要把圖片處理成固定尺寸,同時避免變形。做法是「等比縮放到足以覆蓋目標區域,再居中裁切」,以下用 UIImage 的分類(Category)實作。
#import <Foundation/Foundation.h> @interface UIImage (UIImageExt) - (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize; @end
#import "UIImageExt.h"
@implementation UIImage (UIImageExt)
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize {
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
// 取較大的比例,確保縮放後足以覆蓋整個目標區域
if (widthFactor > heightFactor)
scaleFactor = widthFactor; // 以高度為基準填滿
else
scaleFactor = heightFactor; // 以寬度為基準填滿
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// 居中,讓裁切均勻落在兩側
if (widthFactor > heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor < heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// 這個 context 的尺寸就是最終尺寸,超出部分會被裁掉
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if (newImage == nil)
NSLog(@"could not scale image");
// 記得 pop context,否則會造成記憶體洩漏
UIGraphicsEndImageContext();
return newImage;
}
@end
關鍵在於比例因子(scaleFactor)的選取。如果取兩個方向的較大值,縮放後的圖會同時大於或等於目標寬高,因此必定能完整填滿目標區域,多出的部分被 context 邊界裁掉,視覺上不會留白,這就是「aspect fill」的效果。
反之若取較小值,則是「aspect fit」——整張圖完整可見,但會在某一側留下空白邊條。
UIImage *origin = [UIImage imageNamed:@"big.jpg"]; UIImage *thumb = [origin imageByScalingAndCroppingForSize:CGSizeMake(200, 200)];
1、記得呼叫 UIGraphicsEndImageContext。遺漏會導致 context 堆積,是常見的記憶體洩漏來源。
2、若處理的是大圖(例如 4000×3000 的相機原圖),建議先降採樣再繪製,直接 drawInRect 解 4000px 的圖會佔用大量記憶體。
3、iOS 4 以後可以直接用 sizeInPixel / UIGraphicsImageRenderer(iOS 10+)取代手動 context 管理,程式碼更簡潔。