我正在使用 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 中获取正方形图像
但看起来原始图像仍然不是正方形图像,因此当我执行“UIImage *image = [self scaleImage:img toSize:CGSizeMake(612.0,612.0)];”时仍然会出现倾斜问题。我的假设正确吗?无论如何要缓解这个问题,因为我仍然需要在应用程序的其他地方显示“压缩”图像。
最佳答案
做 myImageView.contentMode = UIViewContentModeScaleAspectFit;
是不够的,因为它以 Zhen 想要的方式改变图像的纵横比,但它不会改变源图像,这就是 Zhen需要。这样做的唯一方法是使用 UIGraphicsImageContext ,如那里所解释的那样:
Resize UIImage with aspect ratio?
关于objective-c - Objective-C : How to fix aspect ratio of image (and not change to fit imageview frame),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6674530/