跳到主要内容

字体

替换字体

Rive 允许你在运行时动态加载和替换字体。这对于需要在 Rive 文件中使用自定义字体或需要根据用户偏好更改字体的应用非常有用。

有关更多信息,请参见加载资源

回退字体

回退字体在主字体中缺少某些字符时使用。你可以配置一个回退字体列表,Rive 将按顺序尝试这些字体,直到找到包含所需字符的字体。

在 iOS 上,为回退字体指定的字体大小将被忽略。取而代之的是,平台选择最匹配文本运行时样式和动画的系统字体。

从 v6.1 开始,在 iOS 和 macOS 上,可以使用多种回退选项。Apple 运行时提供了基于请求的样式选择系统字体的辅助方法。此外,可以直接使用 UIFont / NSFont。

如果没有注册任何回退字体,将使用默认的常规粗细和宽度的系统字体。

// 在应用生命周期的早期,调用类似以下的内容:
RiveFont.fallbackFonts = [
RiveFallbackFontDescriptor(), // 使用默认系统字体
RiveFallbackFontDescriptor(design: .default, weight: .bold, width: .expanded), // 使用粗体、扩展的系统字体
UIFont(name: "...", size: 20)!
]

// 或者,你可以在运行时根据样式提供不同的字体

从 v6.4 开始,在 iOS 和 macOS 上,你可以利用更动态的基于回调的 API 来根据文本运行中任何缺失字符的样式返回不同的字体。

// 与类似的 fallbackFonts API 一样,你可以使用 Rive 辅助类型
// 或原生的 UIFont/NSFont 类型
RiveFont.fallbackFontsCallback = { style in
switch style.weight {
case .thin: return [
RiveFallbackFontDescriptor(weight: .thin),
UIFont.systemFont(ofSize: 20, weight: .thin)
]
case .bold: return [
RiveFallbackFontDescriptor(weight: .bold),
UIFont.systemFont(ofSize: 20, weight: .bold)
]
default: return [
RiveFallbackFontDescriptor(),
UIFont.systemFont(ofSize: 20)
]
}
}

// 或者,你也可以使用原始粗细值来返回各种字体
RiveFont.fallbackFontsCallback = { style in
switch style.rawWeight {
case 100: return [
RiveFallbackFontDescriptor(weight: .thin),
UIFont.systemFont(ofSize: 20, weight: .thin)
]
case 700: return [
RiveFallbackFontDescriptor(weight: .bold),
UIFont.systemFont(ofSize: 20, weight: .bold)
]
default: return [
RiveFallbackFontDescriptor(),
UIFont.systemFont(ofSize: 20)
]
}
}