簡體   English   中英

UIImageView 保持縱橫比,但適合寬度

[英]UIImageView keep aspect ratio, but fit to width

我有一個固定寬度和高度的 UIImageView。 我不想改變 UIImageView 的框架。 我想讓它保存一個圖像,在那里我保持縱橫比,我適合寬度,讓圖像對於 UIImageView 的框架來說要么太高,要么太短。 像這樣:

UIImageView 框架

紅色是 UIImageView 的框架。 灰色是顯示的實際圖像。

我認為最好的方法是使用 imageView 的模式(縱橫比填充、縱橫寬等),這是基於圖像的寬度和高度之間的比率

if image.width > image.height {
    imageView.contentMode = UIViewContentModeScaleAspectFit
    //since the width > height we may fit it and we'll have bands on top/bottom
} else {
  imageView.contentMode = UIViewContentModeScaleAspectFill
  //width < height we fill it until width is taken up and clipped on top/bottom
}

UIViewContentModeScaleAspectFit

通過保持縱橫比縮放內容以適應視圖的大小。 視圖邊界的任何剩余區域都是透明的。

UIViewContentModeScaleAspectFill

縮放內容以填充視圖的大小。 內容的某些部分可能會被裁剪以填充視圖的邊界。

我還沒有測試過,但我覺得這似乎是對的

我認為您需要將圖像縱橫比與 UIImageView 本身的縱橫比進行比較:

private func updateUI() {
    guard let image = image else { return }
    let viewAspectRatio = self.bounds.width / self.bounds.height
    let imageAspectRatio = image.size.width / image.size.height
    if viewAspectRatio > imageAspectRatio {
        self.contentMode = .scaleAspectFill
    } else {
        self.contentMode = .scaleAspectFit
    }
}

override var image: UIImage? { didSet { updateUI() }}

override func layoutSubviews() {
    super.layoutSubviews()
    updateUI()
}

注意:這是方面適合寬度

斯威夫特 5.1 iOS 13

因為我的位於集合視圖的標題單元格上,所以這對我有用:

if headerCell!.imageView.frame.width > headerCell!.imageView.frame.height {
    headerCell!.imageView.contentMode = .scaleAspectFit
    //since the width > height we may fit it and we'll have bands on top/bottom
} else {
     headerCell!.imageView.contentMode = .scaleAspectFill
     //width < height we fill it until width is taken up and clipped on top/bottom
}

對於我的情況下的解決辦法是設置UIImageViewcontentMode基於如果圖像的高度和寬度的比率大於的更大imageView的。

func setupImageViewContentMode() {
    if let image = imageView.image, image.size.height / image.size.width > imageView.frame.height / imageView.frame.width {
        imageView.contentMode = .scaleAspectFit
    } else {
        imageView.contentMode = .scaleAspectFill
    }
}

另外,請注意,您必須根據當前布局進行設置,因此在從后端或任何您需要的地方加載圖像后,例如在layoutSubviews()viewDidLayoutSubviews()調用此方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM