如何从常规UIFont创建粗体UIFont? [英] How do I create a bold UIFont from a regular UIFont?

查看:231
本文介绍了如何从常规UIFont创建粗体UIFont?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 UIFont 对象,是否可以将其转换为粗体?我不知道字体名称,我只有一个UIFont对象。我想要的是一个函数,如

If I have a UIFont object, is it possible to convert it to bold? I don't know the font name, I just have a UIFont object. What I want is a function like

UIFont *boldFontFromFont(UIFont *input)
{
    return [input derivedFontWithFontWeight:UIFontWeightBold];
}

如何更改代码以使其正常工作。 (上面的代码不起作用,我只是说明了这一点。)

How can I change the code so that it works. (The code above does not work, I just made it up to illustrate the point.)

提前致谢。

推荐答案

要获得粗体字体,您需要从字体系列中传递字体的特定名称。您可以从给定字体中获取字体系列名称,然后列出此系列中的所有字体。通常,粗体字体的名称中将包含粗体,但格式不严格,例如可能存在Helvetica-BoldOblique等变体。你可以从这段代码开始:

To get a bold font you need to pass a specific name of the font from a font family. You can get a font family name from a given font, then list all fonts from this family. In general, a bold font will contain "bold" in its name, but the format isn't strict and there could be variations like "Helvetica-BoldOblique", for example. You can start from this code:

- (UIFont *)boldFontFromFont:(UIFont *)font
{
    NSString *familyName = [font familyName];
    NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
    for (NSString *fontName in fontNames)
    {
        if ([fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound)
        {
            UIFont *boldFont = [UIFont fontWithName:fontName size:font.pointSize];
            return boldFont;
        }
    }
    return nil;
}

这篇关于如何从常规UIFont创建粗体UIFont?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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