iOS Quick Tip – Avoid combining animations with setMasksToBounds, if possible

For Random Dice Roller, I wanted to have pretty looking buttons with rounded corners. If you google for something like ‘ios custom button with rounded corners’, you’ll find various examples that use setMasksToBounds and a corner radius, like this:

[button.layer setMasksToBounds:true];
[button.layer setCornerRadius:4.0f];

This was my initial approach, and it worked flawlessly. My button corners were perfectly rounded.

However, when I added animations into the mix, things didn’t quite work out so well. There was a noticeable lag when animating my screens full of buttons with modal-segue-style transitions. I tracked it down to the call to setMasksToBounds. With setMasksToBounds set to false, the animations were liquidy smooth, as expected. But turn it on, and things get choppy.

I didn’t want to release an app with noticeably choppy animations, so I started looking for a solution. Turns out that it’s ridiculously easy to solve the problem – just use a transparent .PNG with the corners already cut out!

Check out my sample project to see the difference in performance.

If you run it on the simulator, it will appear to work fine; run it on your device, though – in my case an iPod Touch 4g – and you will see some significant choppiness.

The moral of the story is that setMasksToBounds can cause performance issues, and if you can avoid it, you should.

2 Comments

  1. thanks a lot! it was exactly the issue that i was having, and removing maskToBounds fixed animation lag. the only question I have is how exactly did you track it down?

    Reply

    1. Glad to hear that it helped! To be honest, I think I tracked it down with a simple “randomly comment stuff out and see how fast it is” process. Definitely no fancy tricks or profilers!

      Reply

Leave a Reply to Marty Dill Cancel reply

Your email address will not be published. Required fields are marked *