首页 文章

缩放字体大小以在UILabel中垂直放置

提问于
浏览
19

我想采用标准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”的示例输出:

uilabel

uilabel subclass

我看过字体下降器和上升器,尝试按照不同的组合考虑这些,但仍然没有任何运气 . 任何想法,这是否与具有不同下降和上升长度的不同字体有关?

2 回答

  • 0

    你对 pointsPerPixel 的计算是错误的,它应该是......

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

    此外,也许这个代码应该在 layoutSubviews 中,因为字体应该更改的唯一时间是帧大小的变化 .

  • 12

    我想知道它是否会在下一个更大的字体大小的情况下出现舍入错误 . 你能稍微调整一下rec.size.height吗?就像是:

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

    Update: 您的pointPerPixel计算是向后的 . 您're actually dividing pixels by font points, instead of points by Pixels. Swap those and it works every time. Just for thoroughness, here'是我测试的示例代码:

    //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字体 . 当我颠倒计算时,我看到相同的结果,字体对于盒子来说太高了 .

相关问题