.h文件:
#import <Foundation/Foundation.h>
@interface UtilMethods : NSObjects
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withImage:(UIImage *)sourceImage;
@end
.m文件:
#import "UtilMethods.h"
@implementation UtilMethods
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withImage:(UIImage *)sourceImage
{
UIImage *newImage = nil;
CGFloat width = sourceImage.size.width;
CGFloat height = sourceImage.size.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledX = 0.0;
CGFloat scaledY = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailRect = CGSizeMake(0.0,0.0,0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor)
scaleFactor = heightFactor; // scale to fit width
else
scaleFactor = widthFactor; // scale to fit height
scaledWidth= width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
scaledY = (targetHeight - scaledHeight)/2;
}
else if (widthFactor < heightFactor)
{
scaledX = (targetWidth - scaledWidth)/2;
}
}
UIGraphicsBeginImageContext(targetSize);
thumbnailRect = CGSizeMake(scaledX,scaledY,scaledWidth,scaledHeight);
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end