2019独角兽企业重金招聘Python工程师标准>>>
图片的等比例缩放可以使用UIImageJPEGRepresentation和UIImagePNGRepresentation函数,需要两个参数:图片的引用和压缩系数.
也可以使用下面的函数
-(UIImage*)buildThumbnailImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
不等比例缩放要考虑图片是fitting or filling
UIImage *BuildThumbnail(UIImage *sourceImage, CGSize targetSize, BOOL useFitting)
{
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0);
// Establish the output thumbnail rectangle
CGRect targetRect = SizeMakeRect(targetSize);
// Create the source image’s bounding rectangle
CGRect naturalRect = (CGRect){.size = sourceImage.size};
// Calculate fitting or filling destination rectangle
CGRect destinationRect = useFitting ? RectByFittingRect(naturalRect, targetRect) : RectByFillingRect(naturalRect, targetRect);
// Draw the new thumbnail
[sourceImage drawInRect:destinationRect];
// Retrieve and return the new image
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return thumbnail;
}
//其中涉及到的几个辅助函数如下:
CGSize SizeScaleByFactor(CGSize aSize, CGFloat factor)
{
return CGSizeMake(aSize.width * factor, aSize.height * factor);
}
CGFloat AspectScaleFill(CGSize sourceSize, CGRect destRect)
{
CGSize destSize = destRect.size;
CGFloat scaleW = destSize.width / sourceSize.width;
CGFloat scaleH = destSize.height / sourceSize.height;
return fmax(scaleW, scaleH);
}
CGFloat AspectScaleFit(CGSize sourceSize, CGRect destRect)
{
CGSize destSize = destRect.size;
CGFloat scaleW = destSize.width / sourceSize.width;
CGFloat scaleH = destSize.height / sourceSize.height;
return fmin(scaleW, scaleH);
}
CGRect RectAroundCenter(CGPoint center, CGSize size)
{
CGFloat halfWidth = size.width / 2.0f;
CGFloat halfHeight = size.height / 2.0f;
return CGRectMake(center.x - halfWidth, center.y - halfHeight, size.width, size.height);
}
CGPoint RectGetCenter(CGRect rect)
{
return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}
CGRect RectByFittingRect(CGRect sourceRect, CGRect destinationRect)
{
CGFloat aspect = AspectScaleFit(sourceRect.size, destinationRect);
CGSize targetSize = SizeScaleByFactor(sourceRect.size, aspect);
return RectAroundCenter(RectGetCenter(destinationRect), targetSize);
}
CGRect RectByFillingRect(CGRect sourceRect, CGRect destinationRect)
{
CGFloat aspect = AspectScaleFill(sourceRect.size, destinationRect);
CGSize targetSize = SizeScaleByFactor(sourceRect.size, aspect);
return RectAroundCenter(RectGetCenter(destinationRect), targetSize);
}
CGRect SizeMakeRect(CGSize size)
{
return (CGRect){.size = size};
}