可变字体 (Variable Fonts)

更轻松地在 AppKit、UIKit 和 SwiftUI 中使用可变字体。适用于 iOS、macOS、tvOS、watchOS 和 visionOS

SwiftUI SwiftUI Swift Xcode MIT

使用可变字体特性扩展了 AppKit 的 NSFont、UIKit 的 UIFont 和 SwiftUI 的 Font。使用起来非常简单!

如何使用

使用轴初始化字体。

let font = NSFont(name: "Amstelvar", size: 20, axes: [
	.weight: 650,
	.opticalSize: 144,
	"GRAD": 500,
])

应用单个轴的新字体

let scienceGothic = UIFont(name: "ScienceGothic", size: 20)!
let slanted = scienceGothic.withAxis(.slant, value: -10)

获取字体的所有可用轴

let tiltWarp = NSFont(name: "TiltWarp-Regular", size: 100)!
let axes = tiltWarp.allAxes()
print(axes)
/*
[VariableFonts.FontAxis(
	id: 1481789268,
	name: "XROT",
	description: "Rotation in X",
	minimumValue: -45.0,
	maximumValue: 45.0,
	defaultValue: 0.0),
etc...]
*/

SwiftUI

Text("Hello world")
	.font(.custom(name: "Fraunces", size: 40, axes: [
		.weight: 900,
		"SOFT": 100,
		"WONK": 1,
	]))

示例:最大化的字体

let nunito = UIFont(name: "NunitoSans", size: 20)!
let axes = nunito.allAxes()

// Creates a UIFont with all axes set to their maximum value.
let megaNunito = nunito.withAxes(
	Dictionary(uniqueKeysWithValues: axes.map { axis in
		return (axis.id, axis.maximumValue)
	})
)

轴名称

您提供的用于配置轴的字典使用 FontAxis.Name 作为键。 此类型带有一组众所周知的轴名称。例如,.weightwght),.widthwdth)等。此类型是 ExpressibleByStringLiteral。字符串文字可用于自定义轴名称。