UIImageView:如何显示缩放图像?

时间:2018-02-08 17:35:12

标签: ios swift uiimageview xcode9.2

我是iOS应用程序开发的新手,我开始学习这个很棒的教程:

开始开发iOS应用程序(Swift)

https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html#//apple_ref/doc/uid/TP40015214-CH6-SW1

一切看起来都不错但是当我试图从模拟器上的“相机胶卷”加载图像时,我得到的图像显示超大并填充所有iPhone模拟器屏幕,而不是仅显示到UIImageView框中,如教程图像所示。 / p>

有趣的事实是,下载课程结束时提供的正确项目(参见页面底部)我也遇到同样的问题。

谷歌搜索我得到一些想法插入:

    // The info dictionary may contain multiple representations of the image. You want to use the original
    guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    // Set photoImageView to display the selected image
    photoImageView.image = selectedImage
    photoImageView.contentMode = UIViewContentMode.scaleAspectFit

    // Dismiss the picker
    dismiss(animated: true, completion: nil)

从相机胶卷加载图像后,但没有结果......

我正在使用Xcode 9.2,部署目标11.2和iPhone 8 plus作为模拟器的目标。

任何帮助都是相关的。

1 个答案:

答案 0 :(得分:2)

这是因为示例代码仅限制UIImageView的比例(您在故事板中添加的1:1约束)。通过这种方式,它将始终保持您的imageView平方,但不会限制大小。

如示例所示,您输入了一个占位符大小,只有在您设置了一些图像之后才会保留。当您在UIImageView上输入新图像时,它会更改为您设置的图像的大小(在您的情况下,可能是相机胶卷的较大图像)。这可能是它变得如此之大的原因。

我认为解决此问题的简单方法是在故事板中添加其他约束以限制大小(例如实际大小或边框约束)。