平时开发的时候经常会遇到需要将图片进行等比缩放的需求,但是本身图片的宽高比与需要等比缩放的宽高比不一致的时候就不方便进行缩放了。
于是我们可以通过对图片进行裁剪来实现修改宽高比:
+ (UIImage *)cutImage:(UIImage*)image
{
CGSize newSize;
CGImageRef imageRef = nil;
UIImageOrientation imageOrientation;
if (image.size.width > image.size.height) {
imageOrientation = UIImageOrientationRight;
if ((image.size.width / image.size.height) < (SCREEN_HEIGHT / SCREEN_WIDTH)) {
newSize.width = image.size.width;
newSize.height = image.size.width * SCREEN_WIDTH / SCREEN_HEIGHT;
imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
} else {
newSize.height = image.size.height;
newSize.width = image.size.height * SCREEN_HEIGHT / SCREEN_WIDTH;
imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
}
} else {
imageOrientation = UIImageOrientationUp;
if ((image.size.width / image.size.height) < (SCREEN_WIDTH / SCREEN_HEIGHT)) {
newSize.width = image.size.width;
newSize.height = image.size.width * SCREEN_HEIGHT / SCREEN_WIDTH;
imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
} else {
newSize.height = image.size.height;
newSize.width = image.size.height * SCREEN_WIDTH / SCREEN_HEIGHT;
imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
}
}
return [UIImage imageWithCGImage:imageRef scale:1.0 orientation:imageOrientation];
}
以上代码将图片分为横图和竖图分别进行了处理。