//图片伸缩到指定大小
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize forImage:(UIImage *)originImage
{
UIImage *sourceImage = originImage;// 原图
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;
// 定位图片的中心点
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else if (widthFactor < heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// 创建基于位图的上下文
UIGraphicsBeginImageContext(targetSize);
// 目标尺寸
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
// 新图片
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
NSLog(@"could not scale image");
// 退出位图上下文
UIGraphicsEndImageContext();
return newImage;
}