issues with UIImageView.layer.cornerRadius to create rounded images on different pixel densities ios

9.4k Views Asked by At

I'm simply trying to create a perfectly round image. Here's my swift code:

myImage.layer.cornerRadius = myImage.frame.size.width/2
myImage.layer.masksToBounds = true

This works on a 4s, but is not quite round on a 5s, and appears as a rounded rectangle on a iphone 6.

I'm assuming this has to do with frame.size.width returning values in pixels not points or something like that, but I've been unable to solve this problem.

5

There are 5 best solutions below

6
On BEST ANSWER

If you're putting that code in viewDidLoad, try moving it to viewDidLayoutSubviews.

I'm guessing it's an auto layout issue -- although you've used the corner radius property appropriately and are in fact making the image frame circular, after auto-layout, the corner radius stays the same, but the image stretches so that it's no longer circular.

1
On

The problem is that if you change the cornerRadius of Any view, and expect it to look like a circle, the view has to be a square.

Now, because of different devices and different device size, the size of your image view might change and it may be a rectangle.

For e.g. If you view is a 50 * 50

myImage.layer.cornerRadius = myImage.frame.size.width/2

This would add corner radios of 25 on both sides to make it a circle.

But because of auto layout of device change, your view might be a 50 * 80

Corner radius would add a 25, but as the height is 80, it will add 25 on both sides, and the remaining 30 won't be a curve and look straight.

What you can do is try viewing the screen in various orientations in the storyboard and change auto layout Constraints (Or structs and springs) to ensure that the image view is a square in all the devices

0
On

If your code is in viewDidLoad in ViewController, try moving it to viewDidLayoutSubviews.

If your rounded imageView is in tableViewCell, try moving it to draw.

override func draw(_ rect: CGRect) {
    avatarView.layer.cornerRadius = avatarView.frame.size.width / 2
    avatarView.layer.masksToBounds = true
    avatarView.clipsToBounds = true
    avatarView.contentMode = .scaleAspectFill
}
0
On

This should work:

myImage.layer.cornerRadius = myImage.**bounds**.size.width/2
myImage.layer.masksToBounds = true
1
On
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

  myImage.layer.cornerRadius  = myImage.frame.size.width/2
  myImage.layer.masksToBounds = true
}