字体
切换字体
你可以在运行时为 Rive 文件切换字体。这在本地化和品牌定制场景中特别有用。
更多信息请参见加载资源。
后备字体
出于安全原因,浏览器不允许直接访问用户的系统字体。因此,必须为此运行时显式提供后备字体。
从 v4.28.0 开始,React 运行时提供了用于提供后备字体的 API。当默认字体无法渲染某个字形时,Rive 将调用你提供的回调来检索要尝试的已解码字体列表。重要的是,此回调必须在 Rive 开始渲染之前注册。
首先,从 React 包中导入 RiveFont 和 decodeFont,并在 Rive 组件开始渲染之前调用 RiveFont.setFallbackFontCallback(),传入回调。回调接收无法渲染的字形(Unicode 码点)和字体粗细,并应返回后备字体列表。如果连续的后备字体也不支持该字形,可能会多次调用回调。
import { useEffect } from "react";
import { useRive, RiveFont, decodeFont } from "@rive-app/react-webgl2";
const THAI_FONT_URL =
"https://raw.githubusercontent.com/google/fonts/main/ofl/notoserifthai/NotoSerifThai%5Bwdth%2Cwght%5D.ttf";
export default function MyRiveComponent() {
useEffect(() => {
const loadFonts = async () => {
const notoSerifThai = await fetch(THAI_FONT_URL).then((res) => res.arrayBuffer());
const riveThaiDecodedFont = await decodeFont(new Uint8Array(notoSerifThai));
RiveFont.setFallbackFontCallback((codePoint: number, weight: number) => {
// 对于泰文,使用 Noto Serif Thai 字体
if (codePoint >= 0x0E00 && codePoint <= 0x0E7F) {
return [riveThaiDecodedFont];
}
return null;
});
};
loadFonts();
}, []);
const { RiveComponent } = useRive({
src: "my.riv",
autoplay: true,
stateMachines: "State Machine 1",
});
return <RiveComponent />;
}