iPhone的开发:任何片段来调整图像大小,并保持比例?

我是在iPhone开发代码的新手,我想search一些代码来调整我的UIImage的大小,但保持比例。 指定的大小就像一个图像不能跨越边界的框架,在该边界内图像应该缩放以适应框架并保持比例,我目前使用的代码可以resize,但不能保持比例,只是粘贴在这里,看看我是否可以做一些微不足道的修改,使其成为可能。

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize { CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height)); CGImageRef imageRef = image.CGImage; UIGraphicsBeginImageContextWithOptions(newSize, NO, 0); CGContextRef context = UIGraphicsGetCurrentContext(); // Set the quality level to use when rescaling CGContextSetInterpolationQuality(context, kCGInterpolationHigh); CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height); CGContextConcatCTM(context, flipVertical); // Draw into the context; this scales the image CGContextDrawImage(context, newRect, imageRef); // Get the resized image from the context and a UIImage CGImageRef newImageRef = CGBitmapContextCreateImage(context); UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; CGImageRelease(newImageRef); UIGraphicsEndImageContext(); return newImage; 

}

好吧,你可以调整图像的尺寸更简单一些:

 + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize { UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } 

那么你需要计算一个维护长宽比的新尺寸。 例如,要获得一个图像一半的大小,你会提供一个像这样创build的大小:

  CGSize halfSize = CGSizeMake(image.size.width*0.5, image.size.height*0.5); 

伪代码用于在保留高宽比的同时将图像调整到特定的边界:

 imageSize // The image size, for example {1024,768} boundarySize // The boundary to fit the image into, for example {960,640} boundaryAspectRatio = boundarySize.width / boundarySize.height imageAspectRatio = imageSize.width / imageSize.height if ( imageAspectRatio == boundaryAspectRatio ) { // The aspect ratio is equal // Resize image to boundary } else if ( imageAspectRatio > boundaryAspectRatio ) { // The image is wider // Resize to: // - Width: boundarySize.width // - Height: boundarySize.height / imageAspectRatio } else if ( imageAspectRatio < boundaryAspectRatio ) { // Resize to: // - Width: boundarySize.width * imageAspectRatio // - Height: boundarySize.height } 

只需将MAX改为MIN即可,而不是Fill;)

 - (UIImage *)imageByFillingSize:(CGSize)newSize useScreenScale:(BOOL)useScreenScale { CGSize size = [self size]; CGRect frame; float ratioW = newSize.width / size.width; float ratioH = newSize.height / size.height; float ratio = MAX(ratioW, ratioH); frame.size.width = size.width * ratio; frame.size.height = size.height * ratio; frame.origin.x = (newSize.width - frame.size.width) / 2.0; frame.origin.y = (newSize.height - frame.size.height) / 2.0; UIGraphicsBeginImageContextWithOptions(newSize, YES, useScreenScale ? 0.0 : 1.0); [self drawInRect:frame]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }