Search code examples
iosswiftrounded-corners

UIView not shows round


For making a circular UIView I am using the cornerRadius property.

I have a UIView with dimension 79*158.

redView.layer.cornerRadius = redView.frame.size.height/2
redView.layer.masksToBounds = true

It shows elipse instead of circle:

It shows elipse instead of circle

Any workaround or does it only work with square type (eg. UIView(100*100))?

I am ok if it resizes dynamically.


Solution

  • use this...

        func makeCircle (view: UIView) {
            view.clipsToBounds = true
            let height = view.frame.size.height
            let width = view.frame.size.width
            let newHeight = min(height, width) // use "max" if you want big circle
    
            var rectFrame = view.frame
            rectFrame.size.height = newHeight
            rectFrame.size.width = newHeight
            view.frame = rectFrame
            view.layer.cornerRadius = newHeight/2
        }
    

    use like this:

    @IBOutlet var rectView: UIView!
    
    override func viewDidLoad() {
            super.viewDidLoad()
    
            makeCircle(view: rectView)
        }