缩放字体大小以垂直适合UILabel [英] Scaling font size to fit vertically in UILabel

查看:170
本文介绍了缩放字体大小以垂直适合UILabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个标准的UILabel和增加字体大小,使其填充垂直空间。从这个问题,我使用这个drawRect实现在UILabel上定义了一个子类:

I want to take a standard UILabel and increase the font size so that it fills the vertical space. Taking inspiration from the accepted answer for this question, I defined a subclass on UILabel with this drawRect implementation:

- (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(w x h),Helvetica作为字体和起始点大小为60,适合舒适的标签。下面是标准UILabel和我的子类使用字符串{Hg:

But this doesn't work as it scales the font beyond the bottom of the label. If you want to replicate this, I started with a label 289x122 (w x h), Helvetica as the font and a starting pointSize of 60 which fits comfortably in the label. Here is example output from the standard UILabel and my subclass using the string "{Hg":

我已经看过字体下降和上升,尝试缩放考虑到这些在不同的组合,但仍然没有任何运气。

I've looked at font descenders and ascenders, tried scaling taking these into account in different combinations, but still haven't had any luck. Any ideas, is this something to do with different fonts having varying descender and ascender lengths?

推荐答案

<$ c $的计算方法是什么? c> pointsPerPixel 是错误的方式,它应该是...

Your calculation for pointsPerPixel is the wrong way up, it should be...

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

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

Also, maybe this code should be in layoutSubviews as the only time the font should be changed is when the frame size changes.

这篇关于缩放字体大小以垂直适合UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆