Swift UIImageView Stretched Aspect

时间:2015-01-15 10:58:33

标签: ios objective-c swift uiimageview

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需要触摸边缘并在屏幕的顶部和底部具有透明空间,并且内部图像需要保持其原始比率而不是拉伸更高。我附上了两张UIImageView中的图像渲染图像。

ImageView with correct Aspect ImageView with wrong Aspect

6 个答案:

答案 0 :(得分:37)

我在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因为我正在使用通过手机摄像头拍摄的图像。

答案 1 :(得分:17)

Swift 3 版本的代码:

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

答案 2 :(得分:14)

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

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

干杯

答案 3 :(得分:6)

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

  

UIViewContentModeScaleAspectFit

     

缩放内容以适合的选项   通过保持纵横比来保持视图的大小。 剩下的   视图边界的区域是透明的。

您所描述的内容似乎需要UIViewContentMode.ScaleAspectFill

  

UIViewContentModeScaleAspectFill

     

将内容缩放到的选项   填充视图的大小。可以剪裁内容的某些部分   填补视图的界限。

答案 4 :(得分:1)

here:有一个很好的解决方案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)
    }

}

答案 5 :(得分:0)

快速5

您只能将 UIView.ContentMode.scaleAspectFit 应用于 UIImageView 像这样:

rf_clf = saveobj(file, "rnd_cv.fit(X_train, np.ravel(y_train))", globals(), locals(), ignore_file=True)