You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字体文件/资源文件夹嵌入Rust二进制及打包为单文件?

Rust游戏字体嵌入与打包解决方案

一、字体嵌入二进制实现方法

既然ttf_context.load_font()只支持路径加载,优先换用支持内存加载的API,不用折腾外部文件:

1. 用对应TTF库的内存加载接口

根据你使用的文本渲染库,选择对应方法:

  • rusttype库:直接用Font::try_from_bytes()读取嵌入的字节数据
use rusttype::Font;

// 把字体文件嵌入二进制
const EMBEDDED_FONT: &[u8] = include_bytes!("./assets/Font.ttf");

// 从内存加载字体
let font = Font::try_from_bytes(EMBEDDED_FONT).expect("加载嵌入字体失败");
  • glyph_brush库:用FontArc::try_from_slice()嵌入字体,再构建渲染器
use glyph_brush::{GlyphBrushBuilder, ab_glyph::FontArc};

const EMBEDDED_FONT: &[u8] = include_bytes!("./assets/Font.ttf");

let font = FontArc::try_from_slice(EMBEDDED_FONT).expect("加载嵌入字体失败");
let text_brush = GlyphBrushBuilder::using_font(font).build();

2. 虚拟文件系统适配(备选)

如果当前库确实没有内存加载能力,可以用memfs创建虚拟文件系统,把嵌入字体写入虚拟路径后再让load_font()读取:

use memfs::MemFs;
use std::io::Write;

let mut virtual_fs = MemFs::new();
// 将嵌入字体写入虚拟路径
let mut virtual_file = virtual_fs.create_file("./assets/Font.ttf").expect("创建虚拟文件失败");
virtual_file.write_all(include_bytes!("./assets/Font.ttf")).expect("写入字体数据失败");
// 后续让ttf_context指向这个虚拟路径(需确保库支持自定义文件系统)

这个方案复杂度高,优先用库自带的内存加载方法。

二、单文件打包方案

1. Windows 单文件.exe

  • 用rust-embed把所有资源嵌入二进制,代码中从内存读取资源,然后执行cargo build --release编译,再用upx压缩(可选),就能得到单文件exe。
  • 或者用cargo-bundle:在Cargo.toml添加配置:
[package.metadata.bundle]
name = "你的游戏名称"
identifier = "com.yourname.yourgame"
version = "0.1.0"
executable = "你的游戏二进制文件名"
resources = ["assets/"]

运行cargo bundle --release,会在target/release/bundle/windows生成包含资源的单文件exe。

2. macOS .app 打包

同样用cargo-bundle,在Cargo.toml配置:

[package.metadata.bundle]
name = "你的游戏名称"
identifier = "com.yourname.yourgame"
version = "0.1.0"
executable = "你的游戏二进制文件名"
resources = ["assets/"]
icon = "assets/icon.icns" # 可选,添加应用图标

运行cargo bundle --release,target/release/bundle/osx下会生成完整的.app包,包含二进制和所有资源,用户可直接双击运行。

内容的提问来源于stack exchange,提问作者Henhen1227

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:40:42