21

我正在使用 UIImagePickerController 为我的应用选择图像。但是,我在保持所选图像的纵横比方面面临一些挑战

例如,

我在手机上有如下原始图像(不是方形图像):

在此处输入图像描述

通过“移动和缩放”页面选择iphone上的图像进行裁剪后,结果如下:(此处仍保持纵横比)

在此处输入图像描述

我的应用程序将在带有方形框架 (200 x 200) 的 UIImageView 中显示所选图像。将所选图像设置为 UIImageView (UIImageView.image = selectedImage) 后,图像的纵横比不会保持不变,而是跟随 UIImageView 的框架:(图像现在在我的 UIImageView 中看起来是倾斜的):

在此处输入图像描述

在这种情况下,有什么办法可以保持图像的纵横比?

编辑:更新预期结果

经过一番思考,我意识到解决我的问题的最佳方法是确保对于此类图像(非方形),我需要将它们“转换”为方形图像,即填充图像顶部和底部的空白空间以制作正方形,例如

预期图像:(添加了顶部和底部边框)

在此处输入图像描述

编辑:使用示例代码更新

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo 
{

    self.imageView.contentMode = UIViewContentModeScaleAspectFill;

    self.imageView.image = image;
    [[picker parentViewController] dismissModalViewControllerAnimated:YES];

    //Compress image
    UIImage *image = [self scaleImage:img toSize:CGSizeMake(612.0,612.0)];

    self.imageData = UIImageJPEGRepresentation(image, 0.75);
}

通过添加代码“self.imageView.contentMode = UIViewContentModeScaleAspectFill;”,我能够在uiimageview中获得方形图像

在此处输入图像描述

But it seems like the original image was still not a square image, hence the skewing problem will still occur when I do "UIImage *image = [self scaleImage:img toSize:CGSizeMake(612.0,612.0)];". Is my assumption correct? Anyway to mitigate this issue as I will still need to display the 'compressed' image elsewhere in the app.

4

3 回答 3

37

myImageView.contentMode = UIViewContentModeScaleAspectFit;是不够的,因为它按照甄想要的方式改变了图像的纵横比,但它并没有改变源图像,这正是甄需要的。做到这一点的唯一方法是使用 UIGraphicsImageContext ,如下所述: Resize UIImage with aspect ratio?

于 2011-07-14T07:25:16.310 回答
23

You should adjust your UIImageView's content mode:

myImageView.contentMode = UIViewContentModeScaleAspectFit;

Just for the kicks - check documentation on UIViewContentMode constants.

于 2011-07-13T05:46:45.190 回答
7

You can set the contentMode property on your UIImageView instance, like:

myImageView.contentMode = UIViewContentModeScaleAspectFit;

This will force it to preserve your image's aspect-ratio when scaling. There are also a number of other values you can set here to produce other behaviors, as described in the reference documentation.

于 2011-07-13T05:47:07.647 回答