UILabel layer cornerRadius negatively impacting performance

For labels, or views with rounded corners and or background colors and shadows on scrolling views the solution is pretty simple:

The biggest issue is from the masksToBounds layer option. This appears to tax performance significantly, however the label seems to need this ON to mask the background color to rounded corners. So to get around this you need to set the labels layer background color instead and switch off masksToBounds.

The second issue is that the default behavior is to redraw the view whenever possible which is totally unnecessary with static or slow changing items on scrolling views. Here we simply set layer.shouldRasterize = YES. This will allow CA to ‘cache’ a rasterized version of the view for quick drawing when scrolling (presumably with hardware acceleration).

You need to make sure your layer has an alpha channel otherwise rasterizing will affect the drawing of rounded corners. I’ve never had a problem as I have alpha set for my background colors, but you may need to check in your situation.

Here is a sample UILabel set up to work nicely on a scollview:

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(4, 4, 40.0, 24.0)];
lbl.font = [UIFont fontWithName:@"Helvetica" size:14.0];
lbl.textAlignment = UITextAlignmentRight;
lbl.text = @"Hello World";
// Must set the label background to clear so the layer background shows
lbl.backgroundColor = [UIColor clearColor];        
// Set UILabel.layer.backgroundColor not UILabel.backgroundColor otherwise the background is not masked to the rounded border.
lbl.layer.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5].CGColor;

lbl.layer.cornerRadius = 8;
lbl.layer.borderColor = [UIColor blackColor].CGColor;
lbl.layer.borderWidth = 1;
// Huge change in performance by explicitly setting the below (even though default is supposedly NO)
lbl.layer.masksToBounds = NO;
// Performance improvement here depends on the size of your view
lbl.layer.shouldRasterize = YES;
lbl.layer.rasterizationScale = [UIScreen mainScreen].scale;
// self here is the child view in the scroll view
[self addSubview:lbl];
[lbl release];

I can fill the iPad 1 screen with views like this and still scroll smoothly 🙂

Leave a Comment