我想采用标准UILabel并增加字体大小以填充垂直空间。从这个question的接受答案中汲取灵感,我使用这个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];
}
但这不起作用,因为它将字体缩放到标签底部之外。如果你想复制它,我开始使用标签289x122(宽x高),Helvetica作为字体,起始点大小为60,适合标签。以下是标准UILabel和我的子类使用字符串“{Hg”:
的示例输出
我看过字体下降器和上升器,尝试按照不同的组合考虑这些,但仍然没有任何运气。任何想法,这与具有不同下降和上升长度的不同字体有关吗?
答案 0 :(得分:12)
您对pointsPerPixel
的计算是错误的,应该是......
float pointsPerPixel = self.font.pointSize / size.height;
此外,也许这段代码应该在layoutSubviews
中,因为字体应该更改的唯一时间是帧大小的变化。
答案 1 :(得分:0)
我想知道它是否会在下一个更大的字体大小的情况下出现舍入错误。你能稍微调整一下rec.size.height吗?类似的东西:
float desiredPointSize = rect.size.height *.90 * pointsPerPixel;
更新:您的pointPerPixel计算是向后的。您实际上是按字体点划分像素,而不是按像素划分点数。交换那些,它每次都有效。为了彻底,这是我测试的示例代码:
//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;
在我测试的每个尺寸的标签盒内缩放并适合,从40pt到60pt字体。当我颠倒计算时,我看到相同的结果,字体对于盒子来说太高了。