objective-c - Objective-C : How to fix aspect ratio of image (and not change to fit imageview frame)

标签 objective-c ios uiimagepickercontroller aspect-ratio

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

例如,

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

enter image description here

通过'移动和缩放'页面选择iphone上的图片裁剪图片后,结果如下:(这里仍然保持纵横比)

enter image description here

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

enter image description here

在这种情况下,有没有办法保持图像的纵横比?

编辑:更新预期结果

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

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

enter image description here

编辑:使用示例代码更新

- (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 中获取正方形图像

enter image description here

但看起来原始图像仍然不是正方形图像,因此当我执行“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/

相关文章:

ios - 如何将 imageView 作为源传递给 QuickLook 预览

ios - iOS 应用程序在后台时的 HTTP 连接,如果离线则重试

ios - 如何在 TextView 中查找多个单词以更改其颜色

ios - NSDictionary initWithContentsOfFile 内存泄漏问题

iphone - Mapkit框架在xcode中不存在

iPhone - 如何处理多个 UIImagePickerControllerDelegate?

ios - 在 UIButton 之间滑动

ios - 为什么 NSUserDefaults 说我要添加一个非属性列表对象?它只是一个带有 NSDictionary、NSNumber 和 NSData 的 NSArray

android - 我们如何在 flutter_riverpod 中没有 ref 对象的情况下访问提供程序?

ios - 将图像加载到 native UIImagePickerController allowsEditing