Search code examples
swiftautolayoutuiimageviewswift5

How to Set UIImageView in circle Swift 5


This code is only working with fix height and width. How can Round UIImageView when we use multiplier?

Here, is the code that Circle my ImageView. Width and Height is 300.

class MusicViewController: UIViewController {

    @IBOutlet weak var imgAlbum: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imgAlbum.layer.borderWidth = 1
        imgAlbum.layer.masksToBounds = false
        imgAlbum.layer.borderColor = UIColor.black.cgColor
        imgAlbum.layer.cornerRadius = imgAlbum.frame.height/2
        imgAlbum.clipsToBounds = true
    }
    
}

enter image description here

If I change my height and width to multiplier like. Now, the multiplier of Height 0.5 and width 0.8. (Proportional height and width to SuperView)

My ImageView Constrain

enter image description here


Solution

  • As @RajaKishan and @aiwiguna both said that you can't get a square image with both proportional height and width constraint together because then you can not get a round circle with different height and width.

    You can set width or height proportional to superview and set the aspect ratio to 1:1 then you can change the multiplier and get the circle properly. You can check to attached image for constraints

    enter image description here

    then set cornerRadius in viewDidLayoutSubviews(), not in viewDidLoad(). (viewDidLoad() is called before the layout constraints change the view height, and only once. viewDidLayoutSubviews() is called any time your view's geometry changes, so you should invoke any layout logic there.

    override func viewDidLayoutSubviews()  {
    
        self.yourImageView.layer.cornerRadius = self.yourImageView.bounds.height/2
        self.yourImageView.clipsToBounds = true
    
    }