Wednesday, 14 September 2011

iPhone SDK Troubles: ios SDK blurry fonts

A very annoying thing is when you programmatically create contents for a UITableViewCell and text in UIlabels appears blurry. Why? The answer is simpler than you can think: you positioned your UILabels in the wrong place. Probably, you positioned your UILabel:
//At allocation time
UILabel* l=[[UILabel alloc] initWithRect:CGRectMake(x,y,w,h)];

//or after
l.frame=CGRectMake(x,y,w,h);
Now, be careful: what's the meaning of (x,y,w,h)? They're floating point values. When placed in a UIView, they must have no fractional part. If you specify it with (e.g.)
(1.0f, 3.0f, 200.0f, 400.0f)
your label will not appears blurry. If you calculate UILabel's frame, you must call floor function to force to zero fractional part.
float a=1.0f;
float b=3.0f;
float c=200.0f;
float d=400.0f;

l.frame=CGRectMake(
        floor(x/3.0f),
        floor(y/3.0f),
        floor(w/3.0f),
        floor(h/3.0f)
    );
Texts appear blurry when coordinates aren't approximate to nearest integer. Floor force this approximation. Now your text will appear sharp as a japanese sword :)
Post a Comment