缩放字体大小以垂直放入UILabel

我想要一个标准的UILabel并增加字体大小,以便填充垂直空间。 从这个问题的被接受的答案中获得灵感,我用这个drawRect实现在UILabel上定义了一个子类:

- (void)drawRect:(CGRect)rect { // Size required to render string CGSize size = [self.text sizeWithFont:self.font]; // For current font point size, calculate points per pixel float pointsPerPixel = size.height / self.font.pointSize; // Scale up point size for the height of the label float desiredPointSize = rect.size.height * pointsPerPixel; // Create and assign new UIFont with desired point Size UIFont *newFont = [UIFont fontWithName:self.font.fontName size:desiredPointSize]; self.font = newFont; // Call super [super drawRect:rect]; } 

但是这不起作用,因为它将字体放大到标签底部以外。 如果你想复制这个,我开始用一个标签289×122(wxh),Helvetica作为字体和起始点大小为60,它符合舒适的标签。 这里是标准UILabel和我的子类使用string“{Hg”的示例输出:

的UILabel

uilabel子类

我已经看过字体下降和上升,试图扩大考虑到不同的组合,但仍然没有任何运气。 任何想法,这是不同的字体具有不同的下行和上行长度?

pointsPerPixel计算是错误的方式,它应该是…

 float pointsPerPixel = self.font.pointSize / size.height; 

另外,也许这个代码应该是在layoutSubviews ,字体应该改变的唯一时间就是帧大小的改变。

我不知道它是一个四舍五入错误思考到下一个更大的字体大小。 你能稍微调整rec.size.height吗? 就像是:

 float desiredPointSize = rect.size.height *.90 * pointsPerPixel; 

更新:您的pointPerPixel计算是向后。 你实际上是通过字体点来分割像素,而不是点像素。 交换这些,每次都有效。 为了彻底,这里是我testing的示例代码:

 //text to render NSString *soString = [NSString stringWithFormat:@"{Hg"]; UIFont *soFont = [UIFont fontWithName:@"Helvetica" size:12]; //box to render in CGRect rect = soLabel.frame; //calculate number of pixels used vertically for a given point size. //We assume that pixel-to-point ratio remains constant. CGSize size = [soString sizeWithFont:soFont]; float pointsPerPixel; pointsPerPixel = soFont.pointSize / size.height; //this calc works //pointsPerPixel = size.height / soFont.pointSize; //this calc does not work //now calc which fontsize fits in the label float desiredPointSize = rect.size.height * pointsPerPixel; UIFont *newFont = [UIFont fontWithName:@"Helvetica" size:desiredPointSize]; //and update the display [soLabel setFont:newFont]; soLabel.text = soString; 

这个尺寸适合我testing的每个尺寸的标签盒,范围从40pt到60pt字体。 当我逆转计算,然后我看到相同的结果,字体太高,不适合框。