标签:
-(UIImage*)scalingAndCroppingImage:(UIImage*)sourceImage forSize:(CGSize)size
{
UIImage *newImage = sourceImage;
CGSize imageSize = sourceImage.size;
CGFloat img_W = imageSize.width;
CGFloat img_H= imageSize.height;
CGFloat bound_W = size.width;
CGFloat bound_H = size.height;
bound_W = bound_W *SCREENSCALE;
bound_H = bound_H *SCREENSCALE;
CGFloat scaleFactor = 0.0;
CGFloat scaled_W = bound_W;
CGFloat scaled_H= bound_H;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
CGFloat widthFactor = bound_W / img_W;
CGFloat heightFactor = bound_H / img_H;
if (widthFactor > heightFactor)
scaleFactor = widthFactor; // scale to fit height
else
scaleFactor = heightFactor; // scale to fit width
scaled_W= img_W * scaleFactor;
scaled_H = img_H * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (scaled_H - bound_H) * 0.5;
}
else if (widthFactor < heightFactor)
{
thumbnailPoint.x = (scaled_W - bound_W) * 0.5;
}
CGRect thumbnailRect = CGRectZero;
thumbnailRect.size.width= bound_W;
thumbnailRect.size.height = bound_H;
if (img_H>=bound_H&&img_W>=bound_W) {
thumbnailRect.origin = thumbnailPoint;
newImage = [self compressImage:sourceImage withSize:CGSizeMake(scaled_W, scaled_H)];
}else{
thumbnailRect.origin.x = (img_W-bound_W)/2;
thumbnailRect.origin.y = (img_H-bound_H)/2;
}
CGImageRef cgimg = CGImageCreateWithImageInRect([newImage CGImage],thumbnailRect);
newImage = [UIImage imageWithCGImage:cgimg];
CGImageRelease(cgimg);
return newImage;
}
- (UIImage *)compressImage:(UIImage *)imgSrc withSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
CGRect rect = {{0,0}, size};
[imgSrc drawInRect:rect];
UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return compressedImg;
}
标签:
原文地址:http://my.oschina.net/u/2330410/blog/401890