Swift UIImageView 拉伸方面

Swift UIImageView Stretched Aspect

UIImageView 渲染图像大小不正确。使用 Scale Aspect Fit,如果 UIImageView 是正方形,则图像是正确的宽高比,在图像未填充的区域具有透明度。

//Image is Square & Correct Size
var imageView = UIImageView(frame: CGRectMake(0, 50, 320, 320))
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.ScaleAspectFit

//Image is Rectangle & Incorrect Size
var imageView = UIImageView(frame: CGRectMake(0, 50, 320, 450))
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.ScaleAspectFit

UIImageView 需要触及边缘并在屏幕的顶部和底部透明 space 并且内部图像需要保持其原始比例而不是拉伸得更高。我附上了两张图像,说明 UIImageView 中的图像是如何渲染的。

这是 UIViewContentMode.ScaleAspectFit 的预期行为。来自文档:

UIViewContentModeScaleAspectFit

The option to scale the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.

从你的描述看来你需要UIViewContentMode.ScaleAspectFill

UIViewContentModeScaleAspectFill

The option to scale the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.

我向 UIImageView 添加了一个自动调整大小的蒙版,它现在显示了正确的比例。

imageView.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth
imageView.contentMode = UIViewContentMode.ScaleAspectFit

这个答案对我有帮助:Captured photo is stretched with AVCaptureSession sessionPreset = AVCaptureSessionPresetPhoto 因为我使用的是通过手机摄像头拍摄的图像。

我遇到了同样的问题,为我解决的是确保在设置内容模式后设置 imageView 图像。即:

    self.imageView.contentMode = UIViewContentMode.ScaleAspectFit
    self.imageView.image = imageChosen

干杯

Swift 3 您的代码版本:

imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
imageView.contentMode = .scaleAspectFit // OR .scaleAspectFill
imageView.clipsToBounds = true

有一个很好的解决方案 by olearyj234
这对我帮助很大。我建议看一看。此外,这是他在 swift 4 和 Xcode 9.2 中的代码:

    class ScaledHeightImageView: UIImageView {

    override var intrinsicContentSize: CGSize {

        if let myImage = self.image {
            let myImageWidth = myImage.size.width
            let myImageHeight = myImage.size.height
            let myViewWidth = self.frame.size.width

            let ratio = myViewWidth/myImageWidth
            let scaledHeight = myImageHeight * ratio

            return CGSize(width: myViewWidth, height: scaledHeight)
        }

        return CGSize(width: -1.0, height: -1.0)
    }

}

Swift 5

您只能为UIImageView申请UIView.ContentMode.scaleAspectFit 像这样:

        let logoImage:UIImage = UIImage(named: "my_logo")!

        let logoImageView = UIImageView(image: logoImage)

        logoImageView.contentMode = UIView.ContentMode.scaleAspectFit

        return logoImageView