【发布时间】:2011-02-08 09:37:05
【问题描述】:
以下代码完美地调整了图像的大小,但问题是它弄乱了纵横比(导致图像倾斜)。有什么指点吗?
// Change image resolution (auto-resize to fit)
+ (UIImage *)scaleImage:(UIImage*)image toResolution:(int)resolution {
CGImageRef imgRef = [image CGImage];
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGRect bounds = CGRectMake(0, 0, width, height);
//if already at the minimum resolution, return the orginal image, otherwise scale
if (width <= resolution && height <= resolution) {
return image;
} else {
CGFloat ratio = width/height;
if (ratio > 1) {
bounds.size.width = resolution;
bounds.size.height = bounds.size.width / ratio;
} else {
bounds.size.height = resolution;
bounds.size.width = bounds.size.height * ratio;
}
}
UIGraphicsBeginImageContext(bounds.size);
[image drawInRect:CGRectMake(0.0, 0.0, bounds.size.width, bounds.size.height)];
UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageCopy;
}
【问题讨论】:
-
查看这个问题(以及我的回答;):stackoverflow.com/questions/1703100/…
-
其他 SO 问题的链接并不是真正的好答案。如果这是重复的,则应照此关闭。
-
这帮助我解决了需要缩放 UIImage 的问题,谢谢 :)