2013-01-24 168 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(圖像的一半尺寸)值與尺寸一起設置,以保持圖像質量。 –