需求:讓 UIImage 依據屏幕寬度等比例縮放高度,避免不同尺寸設備上圖片被拉伸變形。


做法很直接:給 UIImage 寫一個 Category,封裝縮放邏輯。
#import "UIImage+UIImageExtras.h" @implementation UIImage (UIImageExtras) - (UIImage *)imageByScalingToSize:(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; // center the image if (widthFactor < heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } // this is actually the interesting part: UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ; } @end
核心邏輯是取寬高兩個方向的縮放係數中較小的一個,保證內容完整不裁切,多出的空白區域居中對齊。
使用處 import 頭文件後,傳入「屏寬 × 原圖寬高比」作為目標尺寸:
CGSize size = image.size; image = [image imageByScalingToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width * (size.height / size.width))]; self.imageview.image = image;
這樣一來,寬度固定撐滿屏幕,高度按原圖比例伸縮,任何設備上都不會變形。
以上就是 UIImage 按屏寬等比縮放的實例代碼。