NSFont
API有两种不同的方式来指定权重。首先,有一个结构体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,他们从来没有清理过。我错过什么了吗?
这是我想到的映射(通过编写RTF并在TextEdit的字体面板中查看它),截至13.4 Ventura:
NSFont.systemFont(ofSize: 14, weight…)
调用yield (all 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)
}
}