2013-06-28 94 views
0

我正在开发一个应用程序,用户在其中单击图像并上传它们。我的应用程序中有一个按钮,点击它时,相机模式打开。用户可以点击图片并查看预览。在预览图像看起来不错,它占据整个屏幕。稍后,我必须在宽度为110和高度为111的UIImageView中显示此图像。当我在此显示图像时,图像会变形并在边缘处裁剪。我的主要目标是保持宽高比。调整图像保持纵横比

我试过这样做。

- (void)displayCapturedImage 
{ 
//[self.imageView setImage:self.capturedImage]; 
    CGSize smallSize = CGSizeMake(110, 111); 
    [self.imageView setImage:[self imageWithImage:self.capturedImage scaledToSize:smallSize]]; 

} 

- (UIImage*)imageWithImage:(UIImage*)image 
      scaledToSize:(CGSize)newSize; 
{ 
    UIGraphicsBeginImageContext(newSize); 
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; 
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return newImage; 
} 

但这不适合我。图像仍然失真。

回答

1

您需要自己计算比例比例。确定图像需要多小,并将其应用于宽度和高度。

喜欢的东西

float widthFactor = targetWidth/width; 
      float heightFactor = targetHeight/height; 

      if (widthFactor < heightFactor) 
       scaleFactor = widthFactor; 
      else 
       scaleFactor = heightFactor; 

      scaledWidth = width * scaleFactor; 
      scaledHeight = height * scaleFactor; 

      if (widthFactor < heightFactor) 
       thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 

      else if (widthFactor > heightFactor) 
       thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;