The math for that is a little bit hairy, but fortunately, here's a solution I prepared earlier:
- (UIImage *)imageScaledToSize:(CGSize)size
{
//create drawing context
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
//draw
[self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
//capture resultant image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)imageScaledToFitSize:(CGSize)size
{
//calculate rect
CGFloat aspect = self.size.width / self.size.height;
if (size.width / aspect <= size.height)
{
return [self imageScaledToSize:CGSizeMake(size.width, size.width / aspect)];
}
else
{
return [self imageScaledToSize:CGSizeMake(size.height * aspect, size.height)];
}
}
The first function is equivalent to "scale to fill", the second (which calls the first) is equivalent to "aspect fit". These methods were written as a category on UIImage so to use them from within another class you'll need to tweak them by passing the image in as a second parameter (or just make a category on UIImage like I did).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…