iphoneiphone-4sizewithfont

NSString sizeWithFont:constrainedToSize: returning incorrect height on retina displays


I think I have found an edge case for sizeWithFont:constrainedToSize: where, on a retina display, it will sometimes (it seems based on word wrapping) returns a height 1 line taller than is actually needed, and more importantly than is it actually draws.

NOTE: The real code I am using is buried inside performant centric hand drawn variable height table view cell code, so I've distilled the issue down to as simple a bit of sample code as possible. (Please take note of this when trying to answer something other than my question :-)

This sample UIView fills it's content, measures the text to fit (wrapped), fills that rect, then draws the text.

On a retina device (or simulator) the height is returned 1 line too tall, but on a pre-retina device (or simulator) it returns the correct height.

I would greatly appreciate any insight anyone may have, as it is a bug i'd like to fix!

Much Thanks!

-eric

- (void)drawRect:(CGRect)rect {
 NSString * theString = @"Lorem ipsum dolor sit ameyyet, consectetur adipiscing elit. Etiam vel justo leo. Curabitur porta, elit vel.";
 UIFont * theFont = [UIFont systemFontOfSize:12];
 CGSize theConstraint = CGSizeMake(rect.size.width - 20, rect.size.height - 20);
 CGSize theResultSize = [theString sizeWithFont:theFont constrainedToSize:theConstraint];

 // dump the measurements
 NSLog(@"returned a size h = %f, w = %f", theResultSize.height, theResultSize.width);

 // fill the whole rect
 CGContextRef context = UIGraphicsGetCurrentContext();
 [[UIColor yellowColor] set];
 CGContextFillRect(context, rect);

 // fill the measured rect
 CGRect theRect = CGRectMake(10, 10, theResultSize.width, theResultSize.height);
 context = UIGraphicsGetCurrentContext();
 [[UIColor cyanColor] set];
 CGContextFillRect(context, theRect);

 // draw the text
 [[UIColor blackColor] set];
 [theString drawInRect:theRect withFont:theFont];
}

The whole simple project is available here.

Simulator Images:
http://files.droplr.com/files/9979822/aLDJ.Screen%20shot%202011-01-11%20at%2012%3A34%3A34.png http://files.droplr.com/files/9979822/YpCM.Screen%20shot%202011-01-11%20at%2012%3A36%3A47.png


Solution

  • It seems to be an issue with your simulator. This is what I got when I ran it with a Retina simulator on OS 4.3.2

    enter image description here