相对于屏幕尺寸缩放UIFont大小

时间:2014-11-07 07:27:23

标签: ios iphone uifont

我允许用户在图片上添加UITextField,如标题。

我设计了它,以便根据iPhone的屏幕尺寸,它们的图像都是完美的正方形。所以在我的iPhone 5S上,它将是一个320x320 UIImageView。 iPhone 6的容量为375x375 UIImageView。在较小的手机中查看时,较大屏幕手机发布的图像将由imageView缩小。

如何设置相对于屏幕宽度的字体大小?

我目前正在使用:

[UIFont systemFontOfSize:16.0]

使用它是否合适?:

[UIFont systemFontOfSize:self.frame.size.width/20];

我不确定字体大小实际代表什么点大小。我还发现[UIFont preferredFontForTextStyle:UIFontTextStyleBody];,但我不确定这是否是我正在寻找的。

由于

3 个答案:

答案 0 :(得分:1)

UIFont有一个方法可以获取系统字体大小。然后,您可以使用它来动态计算合理的字体大小。什么是合理的将由你来测试和试验。这将导致类似这样的事情:

UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]*[UIScreen mainScreen].bounds.width/375.0];

答案 1 :(得分:1)

它有点矫枉过正,但为了确保我的文字适合屏幕,我正在循环查找字体大小(因为我在自定义drawRect实现中呈现此文本(那里如果您使用UILabel

,可能是更好的方法
    float FACTOR = 0.5f;
    UIFont *font = [UIFont fontWithName:_fontName size:_maximumSize];
    // paragraph for both
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment     = NSTextAlignmentCenter;
    // attributes for back
    NSDictionary *attributes = @{NSFontAttributeName            : font,
                                 NSParagraphStyleAttributeName  : paragraphStyle};
    CGSize textSize   = [_text sizeWithAttributes:attributes];
    // reduce font size until the text fits in bounds
    while(textSize.width > _view.bounds.size.width * FACTOR || textSize.height > _view.bounds.size.height * FACTOR)
    {
        _maximumSize--;
        font       = [font fontWithSize:_maximumSize];
        attributes = @{NSFontAttributeName            : font,
                       NSParagraphStyleAttributeName  : paragraphStyle};
        textSize   = [_progressText sizeWithAttributes:attributes];
    }

只需调整FACTOR即可使字体相对于视图边界适合。

答案 2 :(得分:0)

在Swift 4中:

let textToFit: String = ...
let maxWidth: CGFloat = ...
var font: UIFont = ...
var textAttributes: [NSAttributedStringKey: Any] = [
        .font: font,
        ...
    ]

while (textToFit.size(withAttributes: textAttributes).width > maxWidth)
{
    font = font.withSize(font.pointSize - 1.0)
    textAttributes[.font] = font
}

// You have your font now!
相关问题