Search code examples
iosswiftuiimageviewcornerradius

CornerRadius is not Displayed


I have set the corner radius to 10. But the image view does not show corner radius.

    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.image = UIImage(named: "sample_image")
        imageView.layer.cornerRadius = 20/2
        imageView.contentMode = .scaleToFill
        imageView.clipsToBounds = true
        return imageView

    }()

I have also Tried using imageView.layer.masksToBounds = true but it is also not working.

When I used background color on the image view as follows it shows the view with round corners perfectly.

    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.backgroundColor = UIColor.init(hexString: "#000000")
        imageView.layer.cornerRadius = 20/2
        imageView.contentMode = .scaleToFill
        imageView.clipsToBounds = true
        return imageView

    }()

I also tried changing the image, width and height of the image to check if the image is too large for the view. But it is also not working.

This is how i call the imageView.

       view.addSubview(imageView)

        self.imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        self.imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: imageViewTopMargin).isActive = true

        self.imageView.widthAnchor.constraint(equalToConstant: imageViewWidth).isActive = true

        self.imageView.heightAnchor.constraint(equalToConstant: imageViewHeight).isActive = true

Solution

  • you need to change the contentMode of the UIImageView to center and clipToBound to true.