views:

221

answers:

1

I'm trying to create a simple custom UIView wich contain a string drawn with a single font, but where the first character is slightly larger.

I thought this would be easily implemented with two UILabel:s placed next to eachother.

I use NSString sizeWithFont to measure my string to be able to lay it out correctly.

But I noticed that the font baseline in the returned rectangle varies with +/- 1 pixel depending on the font size I set. Here is my code:

NSString* ctxt = [text substringToIndex:1];
NSString* ttxt = [text substringFromIndex:1];

CGSize sz = [ctxt sizeWithFont: cfont ];
clbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, sz.width, sz.height)];
clbl.text = ctxt;
clbl.font = cfont;
clbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:clbl];

CGSize sz2 = [ttxt sizeWithFont: tfont];
tlbl = [[UILabel alloc] initWithFrame:CGRectMake(sz.width, (sz.height - sz2.height), sz2.width, sz2.height)];
tlbl.text = ttxt;
tlbl.font = tfont;
tlbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:tlbl];

If I use 12.0 and 14.0 as sizes, it works fine. But if I instead use 13.0 and 15.0, then the first character is 1 pixel too high.

Is this a known problem?

Any suggestions how to work around it?

Creating a UIWebView with a CSS and HTML page seems way overkill for this. and more work to handle dynamic strings. Is that what I'm expected to do?

+1  A: 

Found the answer...

Ofcourse, I also have to check the descender value on the font, and compensate for that in the layout.

New rect for the second label is: CGRectMake(sz.width, (sz.height - sz2.height) + floor(cfont.descender - tfont.descender), sz2.width, sz2.height)

floor() is to make sure it snaps to pixel position, or the font will look blurry

Olof Hedman
If you found an answer, please share it.
Alex Reynolds
I thought I did. To be more clear I changed the rect for the second label to: CGRectMake(sz.width, (sz.height - sz2.height) + floor(cfont.descender - tfont.descender), sz2.width, sz2.height)
Olof Hedman