Search code examples
iosswiftuiviewquartz-core

UIView's cornerRadius does not affect view evenly


I am applying cornerRadius normally to a custom view as such:

self.layer.cornerRadius = self.frame.size.height/2

However, I noticed that the resultant corner on the UIView is not evenly applied. Specifically, as seen in the attached photo, the top starts the fade into the corner earlier than the bottom part. While this is zoomed in, the uneven cornering is visible even at normal viewing level. enter image description here

Has anyone also encountered this issue was able to resolve it?


Solution

  • Where do you call this line?

    self.layer.cornerRadius = self.frame.size.height/2
    

    This bug usually happens if cornerRadius is not half of FINAL size. e.g: you set this in viewDidLoad, the height of self is 100, the cornerRadius is now 50, but after self finished layout, its height become 90, the cornerRadius is still 50.

    There are 2 ways to solve this:

    1. If you use fixed constraint for height, you can set cornerRadius anywhere you want: self.layer.cornerRadius = self.someHeightConstraint.constraint / 2

    2. If you don't, set cornerRadius after the view finishes layout (in its superview's viewDidLayoutSubviews)