2013-01-24 164 views

回答

3

使用此代码,这将有助于

+ (UIImage *)scaleImage:(UIImage *)image maxWidth:(int) maxWidth maxHeight:(int) maxHeight 
{ 
    CGImageRef imgRef = image.CGImage; 
    CGFloat width = CGImageGetWidth(imgRef); 
    CGFloat height = CGImageGetHeight(imgRef); 

    if (width <= maxWidth && height <= maxHeight) 
    { 
     return image; 
    } 

    CGAffineTransform transform = CGAffineTransformIdentity; 
    CGRect bounds = CGRectMake(0, 0, width, height); 

    if (width > maxWidth || height > maxHeight) 
    { 
     CGFloat ratio = width/height; 

     if (ratio > 1) 
     { 
      bounds.size.width = maxWidth; 
      bounds.size.height = bounds.size.width/ratio; 
     } 
     else 
     { 
      bounds.size.height = maxHeight; 
      bounds.size.width = bounds.size.height * ratio; 
     } 
    } 

    CGFloat scaleRatio = bounds.size.width/width; 
    UIGraphicsBeginImageContext(bounds.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextScaleCTM(context, scaleRatio, -scaleRatio); 
    CGContextTranslateCTM(context, 0, -height); 
    CGContextConcatCTM(context, transform); 
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef); 

    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return imageCopy; 

} 
+0

帮助?请详细说明你的问题你真的想要做什么 – amar

+0

什么将是正确的图像的宽度和高度? – user2003416

+0

我在查看它。 – user2003416

2

试试这个方法波纹管...

呼叫像波纹管......

UIImage *imgBig = [self imageWithImage:yourImage scaledToSize::yourNewImageSize]; 

,并使用此方法波纹管..

-(UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize 
{ 

    UIGraphicsBeginImageContextWithOptions(newSize, YES, image.scale); 
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 

} 
+0

如果我想保留图像质量,应该是新的图像大小? –

+0

您可以使用图像的原始尺寸将0.5(图像的一半尺寸)值与尺寸一起设置,以保持图像质量。 –