Jan 4, 2013

UIView is blurred after setting its width (autoresizingmask / anchoring related)

Posted Jan 4, 2013
Blurring of views usually occurs when the device is trying to fit 1 point to two pixels. This happens when you have an x or y origin with a decimal place. X or Y origins can have unintentional decimal places when you're setting the "center" property of the view instead of the actual frame. It is more apparent in non-retina devices because they have fewer pixels.

Unintentional decimal places in a view's origin can also occur when you set the width of a view that has an autoresizingmask where the view is automatically anchored to its parent and the system is adjusting the origin for you.

In my experience, I get a blurred view in landscape mode when my I set the width of my anchored view to an odd number, so I just make sure I always set the width to an even number.

CGRect myRect = self.view.frame;
int myRectInt = (int) roundf(myRect.size.width);
if (myRectInt % 2 != 0) {
  myRect.size.width = myRectInt + 1;
self.view.frame = myRect;

Happy coding!

1 comment:

  1. You can use CGRectIntegral(CGRect rect):

    CGRect rect = CGRectMake(0.3, 0.8, 103.33, 55.55);
    NSLog(@"%@ -> %@", NSStringFromCGRect(rect), NSStringFromCGRect(CGRectIntegral(rect)));

    Will output:
    {{0.3, 0.8}, {103.33, 55.55}} -> {{0, 0}, {104, 57}}