需求很單純:把一張圖片先按原比例縮放到能覆蓋目標尺寸的狀態,再從中裁出指定大小的區塊。這樣做的好處是不會讓影像變形,同時又能拿到剛剛好的像素尺寸,常用於縮圖、上傳前的預處理或產生固定尺寸的封面。
+ (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();
[newImage retain];
// 讓 context 出堆疊
UIGraphicsEndImageContext();
return newImage;
}
widthScale、heightScale。UIGraphicsGetImageFromCurrentImageContext 取圖,最後關閉 context。retain 可以移除;autorel ease 的記憶體管理交給 ARC 即可。UIGraphicsBeginImageContext 未指定 scale,在 Retina 螢幕上會以 1x 產生圖片,畫質較鬆。若在意清晰度,建議改用 UIGraphicsBeginImageContextWithOptions(size, NO, 0.0),讓系統依螢幕倍率自動處理。CGRectMake 的 y 偏移改成計算值即可。