我刚刚完成创建一个函数来缓存我在 SDL2 中构建的小型游戏引擎中加载的任何字体,以下函数完美运行,并且渲染文本的速度比每次需要文本时创建新的 SDL_Surface 快大约 12 倍。然而,正如你所看到的,它只缓存 ANSI 字符,这对于英语来说很好,但如果我想翻译我的游戏则不行(德语变音符号或西里尔字母在 ANSI 中不可用)
void cacheFonts(){
for(unsigned int i = 0; i < GlobalFontAssets.size; i++){
SDL_Colour color_font = {255, 255, 255, 255};
std::vector<SDL_Texture*> tempVector;
for(int j = 32; j < 128; j++){
char temp[2];
temp[0] = j;
temp[1] = 0;
SDL_Surface* glyph = TTF_RenderUTF8_Blended(GlobalFontAssets.fonts[i], temp, color_font);
SDL_Texture* texture =
SDL_CreateTextureFromSurface(renderer, glyph);
tempVector.push_back(texture);
SDL_FreeSurface(glyph);
}
GlobalFontAssets.cache.push_back(tempVector);
}
printf("Global Fonts Cached!\n");
}
我尝试过使用wchar_t
,并从0循环到256^2,但是即使使用printf
、wprintf<,我也无法打印任何字符
、cout
和 wcout
,但是如果我这样做:
std::string str = "Привет, öäü"
printf("%s\n", str.c_str());
然后它就可以在终端上打印字符串了。我应该提到,我使用的是 Ubuntu 16.04,因此仅 Windows 的解决方案对我来说不起作用,理想情况下我希望以可移植方式执行此操作。对于那些不熟悉 SDL 的人来说,我所需要的只是一种获取 C 字符串中每个 UTF8 字符的方法。我希望这是可能的。
最佳答案
仅解决问题的这一部分:
all I need is a way to get every UTF8 Character in a C string
Wikipedia has a nice table显示各种编码规则、每个规则涵盖的代码点范围以及相应的 UTF-8 长度和数据字节。
用于覆盖the first 2000-odd characters ,只需生成所有一字节和两字节模式:
char s[3] = { 0 };
for(s[0] = 0x00; s[0] < 0x80u; ++s[0]) { // can start at 0x20 to skip control characters
// one byte encodings
}
for(s[0] = 0xC0u; s[0] < 0xE0u; ++s[0]) {
for(s[1] = 0x80u; s[1] < 0xC0u; ++s[1]) {
// two byte encodings
}
}
值 0x80u
和 0xC0u
在循环条件中出现多次并非巧合 - 事实上,前导字节和后续字节之间没有重叠是什么赋予了 UTF-8 自同步特性。
我猜你依赖的是以下事实(引自维基百科):
The first 128 characters (US-ASCII) need one byte. The next 1,920 characters need two bytes to encode, which covers the remainder of almost all Latin-script alphabets, and also Greek, Cyrillic, Coptic, Armenian, Hebrew, Arabic, Syriac, Thaana and N'Ko alphabets, as well as Combining Diacritical Marks.
由于此范围包含组合标记,因此您将有相当多的条目无法单独呈现。是跳过它们还是仅仅处理文本布局引擎带来的困惑取决于您。
关于c++ - SDL2 中的 UTF 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716356/