Blurry UIViews

Guides | Tutorial By 6 years ago

Back when I owned an iPhone 3GS I often noticed many blurry looking apps, some from small developers and some from Apple themselves (check out the Sales + Updates UISegmentedControl in the iTunes Connect app on an iPhone 3G/3GS). It wasn’t until I started noticing it in my apps that I realised exactly what the problem was. It’s caused by a UIView having it’s origin or size values containing a decimal place. For example if the origin of a view was ‘5’ then it would look crisp, but if it was shifted to ‘5.5’ then it would be blurred to make it seem half way between 5 and 6 because there’s not enough pixels to actually do this. If you are testing on the iPhone 4 then you will miss this as it has enough pixels to actually have a view sit between between the two points. The most common cause for this is setting the view’s center position.

The fix for this is extremely easy, always make sure your origin and size values are exact values. I just cast mine down to integers, which is also quick. My code for this sits within an unblur method defined in a UIView category, which I always call after setting a view’s center.

@interface UIView (Extensions)
@end

@implementation UIView (Extensions)

- (void) unblur
{
	[self setFrame:CGRectMake((int)self.frame.origin.x, (int)self.frame.origin.y, (int)self.frame.size.width, (int)self.frame.size.height)];
}

@end

See the example below, the top label having half pixel coordinates, the bottom being unblurred.

 

You could of course categorise the setCenter: method, but there are some rare cases where blurring is desired.