NSString sizeWithFont:constrainedToSize:在视网膜显示器上返回不正确的高度

时间:2011-01-11 20:46:22

标签: iphone iphone-4 sizewithfont

我想我已经找到了sizeWithFont的一个边缘情况:constrainedToSize:在视网膜显示器上,它有时(似乎基于自动换行)返回高于实际需要的高度1行,更重要的是比它确实吸引了。

注意:我正在使用的真实代码被隐藏在高性能的中心手绘可变高度表视图单元代码中,因此我将问题简化为尽可能简单的示例代码。 (在尝试回答我的问题以外的其他问题时请注意这一点: - )

此示例UIView填充其内容,测量文本以适合(包装),填充矩形,然后绘制文本。

在视网膜设备(或模拟器)上,高度返回1行太高,但在视网膜前设备(或模拟器)上返回正确的高度。

我非常感谢任何人可能拥有的任何洞察力,因为这是我想修复的错误!

非常感谢!

-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];
}

整个简单项目可用here

模拟器图像:
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

3 个答案:

答案 0 :(得分:2)

这似乎与您的模拟器有关。这是我在OS 4.3.2上用Retina模拟器运行时得到的。

enter image description here

答案 1 :(得分:1)

以下是我用于查找动态文本内容标签高度的方法。这在我的应用程序中工作正常


- (float)getHeightFortheDynamicLabel:(NSString *)stringForTheLabel
{
    UITextView *aSampleTextView;
    // 30 is the minimum height
    aSampleTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, mywidth, 30)];
    aSampleTextView.text = stringForTheLabel;
    aSampleTextView.font = [UIFont systemFontOfSize:kMyFontSize];
    aSampleTextView.alpha = 0;
    [self.view addSubview:aSampleTextView];
    float textViewHeight = aSampleTextView.contentSize.height;
    [aSampleTextView removeFromSuperview];
    [aSampleTextView release];
    return  textViewHeight;
}

答案 2 :(得分:0)

        NSString *strSubstring = @"asdfghjklasdfghjkl adsds";

        CGFloat maxWidth = 205.0;
        CGFloat maxHeight = 9999;
        CGSize maximumLabelSize = CGSizeMake(maxWidth,maxHeight);
        CGSize expectedLabelSize = [strSubstring sizeWithFont:[UIFont fontWithName:@"StagSans-Light" size:12] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap];

        NSLog(@"returned a size h = %f, w = %f", expectedLabelSize.height, expectedLabelSize.width);

        return expectedLabelSize;