我想我找到了 sizeWithFont:constrainedToSize: 的边缘情况:在视网膜显示器上,它有时(它似乎基于自动换行)返回的高度比实际需要的高 1 行,而且比它实际绘制的更重要.
注意:我使用的真实代码隐藏在以性能为中心的手绘可变高度表视图单元代码中,因此我已将问题提炼为尽可能简单的示例代码。(尝试回答我的问题以外的问题时请注意这一点:-)
此示例 UIView 填充其内容,测量文本以适应(包装),填充该矩形,然后绘制文本。
在视网膜设备(或模拟器)上,返回的高度太高了 1 行,但在预视网膜设备(或模拟器)上,它返回正确的高度。
我将非常感谢任何人可能拥有的任何见解,因为这是我想修复的错误!
非常感谢!
-埃里克
- (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];
}
整个简单的项目都可以在这里找到。
模拟器图像: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