位图文本
🌐 Bitmap Text
BitmapText 是 PixiJS 中的高性能文本渲染解决方案。与将每个字符串栅格化为新纹理的 Text 类不同,BitmapText 从预生成的纹理图集中绘制字符。这种设计允许你以最小的开销渲染成千上万的文本对象。
import { Assets, BitmapText } from 'pixi.js';
await Assets.load('fonts/MyFont.fnt');
const text = new BitmapText({
text: 'Loaded font!',
style: {
fontFamily: 'MyFont',
fontSize: 32,
fill: '#ffcc00',
},
});
为什么使用 BitmapText?
🌐 Why Use BitmapText?
- ✅ 快速渲染:非常适合HUD、分数计数器、计时器等。
- ✅ 无需逐帧光栅化:文本更改成本低。
- ✅ 高效的内存使用:在所有实例之间共享字形纹理。
- ✅ 支持 MSDF/SDF 字体:缩放清晰,无模糊。
理想使用场景:
- 频繁更新文本
- 大量文本实例
- 高性能或移动项目
如何加载和使用位图字体
🌐 How to Load and Use Bitmap Fonts
字体加载
🌐 Font Loading
PixiJS 支持 AngelCode BMFont 格式和兼容 MSDF 的 .fnt 和 .xml 文件。你可以使用 Assets API 加载这些文件。
🌐 PixiJS supports AngelCode BMFont format and MSDF-compatible .fnt and .xml files. You can load these files using the Assets API.
加载后,你可以使用 fontFamily 属性和已加载的字体创建一个 BitmapText 实例。
🌐 Once loaded, you can create a BitmapText instance with the loaded font using the fontFamily property.
import { Assets, BitmapText } from 'pixi.js';
await Assets.load('fonts/MyFont.fnt');
const text = new BitmapText({
text: 'Loaded font!',
style: {
fontFamily: 'MyFont',
fontSize: 32,
fill: '#ffcc00',
},
});
MSDF 和 SDF 字体
🌐 MSDF and SDF Fonts
PixiJS 支持 MSDF(多通道有符号距离场)和 SDF 格式,以实现清晰、分辨率无关的文本。这些字体在任何大小和缩放下都保持清晰锐利。
🌐 PixiJS supports MSDF (multi-channel signed distance field) and SDF formats for crisp, resolution-independent text. These fonts remain sharp at any size and scale.
你可以使用像 AssetPack 这样的工具生成 MSDF/SDF 字体,它可以使用 .ttf 或 .otf 字体并生成带有 MSDF/SDF 支持的位图字体图集。
🌐 You can generate MSDF/SDF fonts using tools like AssetPack which can take a .ttf or .otf font and generate a bitmap font atlas with MSDF/SDF support.
使用 MSDF/SDF 字体与使用常规位图字体类似,只需加载相应的字体文件即可:
🌐 Using MSDF/SDF fonts is similar to using regular bitmap fonts and just requires you to load the appropriate font file:
import { Assets, BitmapText } from 'pixi.js';
await Assets.load('fonts/MyMSDFFont.fnt');
const text = new BitmapText({
text: 'Loaded MSDF font!',
style: {
fontFamily: 'MyMSDFFont',
},
});
限制和警告
🌐 Limitations and Caveats
❌ 无法更新分辨率
🌐 ❌ Cannot Update Resolution
BitmapText.resolution 是不可变的。它必须由 BitmapFont 处理
text.resolution = 2;
// ⚠️ [BitmapText] dynamically updating the resolution is not supported.
⚠️ 大字符集不实用
🌐 ⚠️ Large Character Sets Not Practical
位图字体受纹理大小限制。CJK 或表情符号丰富的字体集可能需要过多内存。使用 Text 或 HTMLText 以支持动态国际化或表情符号。
🌐 Bitmap fonts are limited by texture size. CJK or emoji-rich sets may require too much memory. Use Text or HTMLText for dynamic internationalization or emoji support.
API 参考
🌐 API Reference