Tolga Karameşe
Tolga Karameşe

Reputation: 23

Swift circular corners doesn't work properly on different screen sizes

I'm trying to achieve smooth round corners on imageviews. Although it's working well on non-plus devices, i can not reach my goal at plus screen devices. Incidentally, i recognize, it's not even work well on the devices that font size enlarged. I applied following code that can be found every topic.

    mergedImage.image = lastImage
    mergedImage.layer.masksToBounds = false
    mergedImage.layer.cornerRadius = mergedImage.frame.size.height / 2
    mergedImage.clipsToBounds = true

And it's results like pictures below.

At iPhone 8 Plus

At iPhone X

At iPhone 5S

Upvotes: 0

Views: 713

Answers (1)

Rengers
Rengers

Reputation: 15218

It looks like the black shape changes size. This can happen when using AutoLayout for example. If that is the case, you need to calculate the corner radius each time the frame changes.

I think the best way to do this is by subclassing UIView to create a "black shape view", and then overriding its layoutSubviews method:

override func layoutSubviews() {
  super.layoutSubviews()
  layer.cornerRadius = bounds.height / 2
}

If you don't have a subclass, you can for example do this in UIViewController.viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {
  super.viewDidLayoutSubviews()
  mergedImage.layer.cornerRadius = bounds.height / 2
}

Upvotes: 5

Related Questions