NSFont.Weight 和整数值之间是否存在映射?

问题描述 投票:0回答:1

NSFont
API 有两种不同的方法来指定权重。首先,有一个 struct
NSFont.Weight
,它包含一个浮点
rawValue
属性。它用于以下功能:

NSFont.systemFont(ofSize fontSize: CGFloat, weight: NSFont.Weight) -> NSFont

然后还有一个获取其他字体的函数,它使用了一个整数。

NSFontManager.font(withFamily family: String, traits: NSFontTraitMask, 
                   weight: Int, size: CGFloat) -> NSFont?

该函数的文档说整数不仅仅是浮点数的四舍五入版本。

weight
可以在 0-15 范围内,其中 5 是正常重量。但是:

NSFont.Weight.regular.rawValue == 0.0
NSFont.Weight.light.rawValue == -0.4000000059604645
NSFont.Weight.black.rawValue == 0.6200000047683716

我没有看到任何提及如何在

NSFont.Weight
和整数之间进行转换。也许这只是一些他们从未清理过的奇怪的遗留 API。我错过了什么吗?

appkit nsfont nsfontmanager
1个回答
0
投票

这是我想出的映射(通过编写 RTF 并在 TextEdit 的字体面板中查看),截至 13.4 Ventura:

NSFont.systemFont(ofSize: 14, weight…)
调用 yield(所有 Helvetica Neue):

.ultraLight // UltraLight
.light // Light
.thin // Thin
.medium // Medium
.semiBold // Bold
.bold // Bold
.heavy // Bold
.black // Bold

NSFontManager.shared.font(…weight: intWeight…)
调用 yield:

weight: 0-2 // UltraLight
weight: 3 // Thin
weight: 4-5 // Regular
weight: 6-7 // Medium
weight: 8-10 // Bold
weight: 11-15 // Condensed Black

人为:

extension NSFont
{
    /// Rough mapping from behavior of `.systemFont(…weight:)`
    /// to `NSFontManager`'s `Int`-based weight,
    /// as of 13.4 Ventura
    func withWeight(weight: NSFont.Weight) -> NSFont?
    {
        let fontManager=NSFontManager.shared

        var intWeight: Int

        switch weight
        {
        case .ultraLight:
            intWeight=0
        case .light:
            intWeight=2 // treated as ultraLight
        case .thin:
            intWeight=3
        case .medium:
            intWeight=6
        case .semibold:
            intWeight=8 // treated as bold
        case .bold:
            intWeight=9
        case .heavy:
            intWeight=10 // treated as bold
        case .black:
            intWeight=15 // .systemFont does bold here; we do condensed black
        default:
            intWeight=5 // treated as regular
        }

        return fontManager.font(withFamily: self.familyName ?? "",
                                traits: .unboldFontMask,
                                weight: intWeight,
                                size: self.pointSize)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.