使用符号特征从 *light* 字体创建斜体版本

Creating an italic version from a *light* font using symbolic traits

我想要一个斜体版本的浅色字体,例如 "HelveticaNeue-Light"。

使用 fontDescriptor 给我 'regular' "Helvetica Neue" 的斜体版本,而不是斜体 "HelveticaNeue-Light"。我可以检索 fontDescriptor.fontAttributes 并更新 UIFontDescriptor.AttributeName.name,但这很棘手,因为每种字体的命名都不同("HelveticaNeue" 使用 "Italic",Helvetica 使用 "Oblique") .

let lightFont = UIFont(name: "HelveticaNeue-Light", size: 16.0)!
var lightFontDescriptor = lightFont.fontDescriptor.withSymbolicTraits([.traitItalic])!
var lightFontWithItalicTraits = UIFont(descriptor: lightFontDescriptor, size: 0)

// <UICTFont: ..> font-family: "HelveticaNeue-Light"; font-weight: normal; font-style: normal; font-size: 16.00pt
print(lightFont)

// <UICTFont: ..> font-family: "Helvetica Neue"; font-weight: normal; font-style: italic; font-size: 16.00pt
print(lightFontWithItalicTraits)

// The font I expect:
let lightItalicFont = UIFont(name: "HelveticaNeue-LightItalic", size: 16.0)!
// <UICTFont: ..> font-family: "HelveticaNeue-LightItalic"; font-weight: normal; font-style: italic; font-size: 16.00pt
print(lightItalicFont)

关于如何获得现有字体的斜体版本还有其他想法吗?

它不是最漂亮的,但它很实用。它处理所有内置 iOS 字体。

分机:

extension UIFont {
    func italic() -> UIFont? {
        if let italic = UIFont.init(name: "\(self.fontName)-Italic", size: self.pointSize) {
            return italic
        } else if let italic = UIFont.init(name: "\(self.fontName)Italic", size: self.pointSize) {
            return italic
        }
        if let oblique = UIFont.init(name: "\(self.fontName)-Oblique", size: self.pointSize) {
            return oblique
        } else if let oblique = UIFont.init(name: "\(self.fontName)Oblique", size: self.pointSize) {
            return oblique
        }
        var suffixFontName = self.fontName // for font names that have a 2 letter suffix such as ArialMT
        suffixFontName.removeLast(2)
        let suffix = self.fontName.suffix(2)
        if let suffixFontName = UIFont.init(name: "\(suffixFontName)-Italic\(suffix)", size: self.pointSize) {
            return suffixFontName
        }
        if let suffixFontName = UIFont.init(name: "\(suffixFontName)Italic\(suffix)", size: self.pointSize) {
            return suffixFontName
        }
        // no italic, oblique, or mt italic font found
        return nil
    }
}

用法:

    let helveticaNeueLightItalic = UIFont(name: "HelveticaNeue-Light", size: 16.0)!.italic()
    print(helveticaNeueLightItalic)

    let helveticaItalic = UIFont(name: "Helvetica", size: 16.0)!.italic()
    print(helveticaItalic)

    let helveticaLightItalic = UIFont(name: "Helvetica-Light", size: 16.0)!.italic()
    print(helveticaLightItalic)

    let arialMtItalic = UIFont(name: "ArialMT", size: 16.0)!.italic()
    print(arialMtItalic)

    let arialMtBoldItalic = UIFont(name: "Arial-BoldMT", size: 16.0)!.italic()
    print(arialMtBoldItalic)