Masked And Animated Corners

Apple loves a rounded rectangle. They even sneaked a couple of improvements into iOS 11. I saw these two tips during WWDC 2017 and then forgot about them.

Masked Corners

You are most likely familiar with the technique of setting a corner radius using the Core Animation layer of a view.

let blueView = UIView()
blueView.backgroundColor = .blue
blueView.layer.cornerRadius = 25.0
// ...view setup...

The cornerRadius works on the background color of the layer. Here is the resulting rounded blue rectangle:

Blue view with rounded corners

But what if I did not want to round all four corners? Well there is good news in iOS 11. There is now a maskedCorners property for the layer. This is a CACornerMask which has four possible values for each corner:

Including a value results in that corner appearing rounded. It defaults to all four corners. If I wanted only the top left and bottom right corners rounded:

if #available(iOS 11, *) {
  blueView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]
}

Which gives me this work of art:

Blue view with masked corners

CornerRadius Now Animatable

More good news for lovers of rounded rectangles. Starting in iOS 11 the cornerRadius property is now an animatable property so you can do this with a standard UIView animation block:

if #available(iOS 11, *) {
  UIView.animate(withDuration: duration, animations: {
    self.blueView.layer.cornerRadius = radius
  }, completion: { _ in
    UIView.animate(withDuration: duration, animations: {
      self.blueView.layer.cornerRadius = 0
    })
  })
}

The result of combining masked corners with an animating corner radius:

Animating corner radius

Further Details

Never miss a post!

iOS Size Classes Cheat Sheet

Subscribe and get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
No time to watch WWDC videos?

Sign up to get my iOS posts direct to your inbox and I will send you a free PDF of my iOS Size Classes Cheat Sheet.

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
Archives Categories