Search code examples
iosswiftautolayout

Corner radius wrong - circular image looks like an eye


I'm trying to make a circular image in Swift, I've searched around and watched a couple YouTube videos. The solutions proposed are extremely easy, but when I used them I get an image formed as an eye instead of a circle, below is my view controller and a picture of the UI

var experimentIdentifier: String = ""


@IBOutlet weak var foregroundImage: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()

    foregroundImage.layer.cornerRadius = (foregroundImage.frame.size.width) / 2
    foregroundImage.layer.masksToBounds = true
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

Supposed to be a circular image


Solution

  • It's because your image is not a square.

    See this problem in action:

    Set the image to a width : height = 2 : 1 rectangle in storyboard

    enter image description here

    then run, the image will look like

    enter image description here

    but if the image is a square, like this in storyboard

    enter image description here

    click run, it'll be like

    enter image description here

    Enjoy coding!