Search code examples
iosswiftswift3uiimageviewuiimage

ios UIImage going outside of UIImageView Border


Here black border shows the Parent UIView of UIImageView and Red border showing UIImageView i'm downloading image from server but the image is going outside of the UIImageView area as shown in the image. I'm doing it programmatically any help would be very much appreciated. I'm adding code block below

enter image description here

let bottomView : UIView = UIView(frame: CGRect(x : 10, y: stackView.height, width: view.width * 0.75, height: view.width * 0.75 ))

view.addSubview(bottomView)

bottomView.layer.borderColor = UIColor.black.cgColor
bottomView.layer.borderWidth = 1

bottomView.translatesAutoresizingMaskIntoConstraints = false
bottomView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
bottomView.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: -20).isActive = true
bottomView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
bottomView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
bottomView.widthAnchor.constraint(equalToConstant: view.width * 0.75).isActive = true
bottomView.heightAnchor.constraint(equalToConstant: view.width * 0.75).isActive = true

let imageView : UIImageView = UIImageView(frame : CGRect(x: 0, y: 0, width: 250, height: 250 ))

 imageView.layer.borderColor = UIColor.red.cgColor
 imageView.layer.borderWidth = 1
 bottomView.addSubview(imageView)

 imageView.translatesAutoresizingMaskIntoConstraints = false
 imageView.centerXAnchor.constraint(equalTo: bottomView.centerXAnchor).isActive = true
 imageView.centerYAnchor.constraint(equalTo: bottomView.centerYAnchor).isActive = true
 imageView.widthAnchor.constraint(equalToConstant: 250).isActive = true
 imageView.heightAnchor.constraint(equalToConstant: 250).isActive = true
 imageView.downloadedFrom(link: (sizeResult?.results![0].data?.size_Chart?.mobile_image?.imageValue?.imageMain?.url)!, contentMode : .scaleAspectFill)

this bottomView will be added UIAlertViewController.

This image shows ** contentMode is Aspect Fit **


Solution

  • Set the properties of uiimageview and content mode:

    self.imageView.clipsToBounds = true
    self.imageView.contentMode = .scaleAspectFit