Tuesday, 11 August 2009

UITextField fuzzy/blurred text

I just solved a very obscure bug where the text in a UITextField can be rendered with a slight blur/anti-aliasing effect. The text will appear crisp when it becomes the first responder, then return to being blurred when it loses focus:

Example of blurred text

I found a number of references to this bug through Google, but everybody worked around it by playing with font sizes. After much hunting I found this thread that says anti-aliasing is applied when a view's frame contains fractional pixel values, e.g. if you calculate its size or position as a fraction of the super view.

Sure enough, casting the CGRect values to (int) for the view's frame worked perfectly. So as an example, if you wanted your text field to be centered vertically in the superview, you should use an (int) cast like this:

textFieldWidth = 300;
textFieldHeight = 31;
offsetX = 0;
offsetY = (superview.bounds.size.height - textFieldHeight) / 2;

textField.frame = CGRectMake((int) offsetX,
                             (int) offsetY,
                             (int) textFieldWidth,
                             (int) textFieldHeight);

Unfortunately, if you are trying to use UITextFields inside table view cells, you have no control over the parent cell's frame, so you might find this fix doesn't work for you if the parent view has fractional values in its frame.

Also see the post on stackoverflow.com.

2 comments:

  1. i tried your solution. in my case changing min font size and font size helped.

    ReplyDelete
  2. Thanks! That fixed my problem. The width and origin's x value of the frame was fractional. Casting to int before assigning, the problem went away!

    ReplyDelete