Alignment UIImageView with Aspect Fit

Viewed 95923

for my UIImageView I choose Aspect Fit (InterfaceBuilder) but how can I change the vertical alignment?

12 Answers

I came up to the following solution:

  1. Set UIImageView content mode to top: imageView.contentMode = .top
  2. Resize image to fit UIImageView bounds

To load and resize image I use Kingfisher:

let size = imageView.bounds.size
let processor = ResizingImageProcessor(referenceSize: size, mode: .aspectFit)
imageView.kf.setImage(with: URL(string: imageUrl), options: [.processor(processor), .scaleFactor(UIScreen.main.scale)])

If you need to achieve aspectFit and get rid empty spaces

Dont forget to remove width constraint of your imageview from storyboard and enjoy

class SelfSizedImageView :UIImageView {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let imageSize = image?.size else {
            return
        }
        
        let viewBounds = bounds
        let imageFactor = imageSize.width / imageSize.height
        let newWidth = viewBounds.height * imageFactor
        
        let myWidthConstraint = self.constraints.first(where: { $0.firstAttribute == .width })
        myWidthConstraint?.constant = min(newWidth, UIScreen.main.bounds.width / 3)
        
        layoutIfNeeded()
    }}

Credit to @michael-platt

Key Points

  • imageView.contentMode = .scaleAspectFit
  • let width = Layout.height * image.size.width / image.size.height
  • imageView.widthAnchor.constraint(equalToConstant: width).isActive = true

Code:

func setupImageView(for image: UIImage) {
    let imageView = UIImageView()
    imageView.backgroundColor = .orange

    //Content mode
    imageView.contentMode = .scaleAspectFill
    
    view.addSubview(imageView)

    //Constraints
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true

    //Feel free to set the height to any value
    imageView.heightAnchor.constraint(equalToConstant: 150).isActive = true

    //ImageView width calculation
    let width = Layout.height * image.size.width / image.size.height
    imageView.widthAnchor.constraint(equalToConstant: width).isActive = true
}
Related