size:
您传入的是-[UIFont fontWithName:size:]
字体的磅值。
您返回的大小是字符串中布局字形-[NSString sizeWithFont:constrainedToSize:lineBreakMode:]
的实际大小。
如果您希望给定的字符串具有特定的大小,在特定的面上,您可能必须进行牛顿方法类型迭代,在其中更改您传入的点大小,直到布局大小足够接近你要。(顺便说一句,我不希望这样的操作在一般情况下会很快。)它可能看起来像这样:
NSString* theString = @"FOOBAR";
CGSize constraint = CGSizeMake(275, 12);
CGFloat desiredHeight = 12.0;
CGFloat pointSize = desiredHeight;
CGFloat actualHeight = 0;
do {
CGSize size = [theString sizeWithFont: [UIFont fontWithName:@"Helvetica" size: pointSize] constrainedToSize: constraint lineBreakMode:NSLineBreakByTruncatingTail];
actualHeight = size.height;
CGFloat ratio = actualHeight / desiredHeight;
pointSize = pointSize / ratio;
} while (fabs(actualHeight - desiredHeight) > 0.01);
PS:-[NSString sizeWithFont:constrainedToSize:lineBreakMode:]
在 iOS7 中已弃用。编译器告诉我-boundingRectWithSize:options:attributes:context:]
改用。使用新的推荐方法,它可能如下所示:
NSString* theString = @"FOOBAR";
CGSize constraint = CGSizeMake(275, 12);
CGFloat desiredHeight = 12.0;
CGFloat pointSize = desiredHeight;
CGFloat actualHeight = 0;
NSStringDrawingContext* ctx = [[NSStringDrawingContext alloc] init];
do {
CGRect br = [theString boundingRectWithSize: constraint options: 0 attributes: @{ NSFontAttributeName : [UIFont fontWithName:@"Helvetica" size: pointSize] } context:ctx];
actualHeight = br.size.height;
CGFloat ratio = actualHeight / desiredHeight;
pointSize = pointSize / ratio;
} while (fabs(actualHeight - desiredHeight) > 0.01);