Yogesh Patel
Yogesh Patel

Reputation: 2017

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

Upvotes: 0

Views: 1700

Answers (2)

Kishan Bhatiya
Kishan Bhatiya

Reputation: 2368

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

}

Upvotes: 1

aiwiguna
aiwiguna

Reputation: 2922

you will not get a square by using proportional width and proportional height constraint together like that, in different device it will have different height and width

my suggestion is to use only one proportional width or proportional height (which one you want) and use aspect ratio constraint 1:1 on the view

Upvotes: 1

Related Questions