如何在我的 Android NDK 项目中包含字体文件 (.ttf)?

iHo*_*ell 2 android freetype freetype2 android-ndk

因此,我需要在我的 Android NDK 项目中包含用于 Freetype 字体渲染的 .ttf 字体文件。我应该把它放在哪里才能将其放入 apk 中?

小智 5

我将添加我的解决方案,它是通过传递 assetManager,并在 c++ 端保留对它的引用。字体 ttf 文件存储在 fonts 文件夹内的 asset 文件夹中。

FT_library library;
FT_Face fontFace;

AAsset* fontFile = AAssetManager_open(manager, "fonts/Roboto-Medium.ttf", AASSET_MODE_BUFFER);
off_t fontDataSize = AAsset_getLength(fontFile);

FT_Byte* fontData = new FT_Byte[fontDataSize];
AAsset_read(fontFile, fontData, (size_t) fontDataSize);
AAsset_close(fontFile);


if (FT_Init_FreeType(&library)) {
    LOGE("Could not load library");
}
if (FT_New_Memory_Face(library, (const FT_Byte*)fontData, (FT_Long)fontDataSize, 0, &fontFace)) {
    LOGE("Load memory failed");
}
Run Code Online (Sandbox Code Playgroud)

要传递 assetManager,只需将其作为对象传递并在 C++ 端进行转换。

AAssetManager *manager = AAssetManager_fromJava(javaEnv, assetObject);
Run Code Online (Sandbox Code Playgroud)