首页 > 解决方案 > 字体资源加载/显示位图问题

问题描述

我正在尝试从 .ttf 文件加载字体(arial)并使用 STB TrueType 库:https ://github.com/nothings/stb/blob/master/stb_truetype.h并将其显示在屏幕上。

它在显示字符数组“a”中的第一个字母时工作,但之后的每个字符看起来都扭曲和奇怪,请参见下面的示例

输出为“a”(正确):

正确的

应该是'b':

不正确

我想也许我误解/误用了内存最终是如何布局的,或者文件是如何被读取的?

以下是相关代码:

(在win32平台层文件中)

struct character_bitmap
{
    unsigned char* memory;
    int width;
    int height;
};

struct font_buffer
{
    character_bitmap* memory;
    float size;
};

static font_buffer font_bitmaps;

void test_load_arial(float size)
{
    if (font_bitmaps.memory)
    {
        // VirtualFree(font_bitmaps.memory, 0, MEM_RELEASE);
        free(font_bitmaps.memory);
    }

    unsigned char* ttf_buffer = (unsigned char*)malloc(1 << 25);
    stbtt_fontinfo font;

    fread(ttf_buffer, 1, 1 << 25, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
    stbtt_InitFont(&font, (unsigned char*)ttf_buffer, stbtt_GetFontOffsetForIndex((unsigned char*)ttf_buffer, 0));

    // int char_bitmap_width = (int)size;
    // int char_bitmap_height = (int)size;

    // unsigned int character_memory_size = ((int)size * (int)size) * 4 /*+ 8*/;
    // int font_memory_size = character_memory_size * 52;

    unsigned int font_memory_size = sizeof(character_bitmap) * 52;

    // font_bitmaps.memory = (character_bitmap*)VirtualAlloc(0, font_memory_size, MEM_COMMIT, PAGE_READWRITE);
    font_bitmaps.memory = (character_bitmap*)malloc(font_memory_size);

    char alphabet[53] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    character_bitmap* current_character = font_bitmaps.memory;
    for (int i = 0; i < 52; i++)
    {
        // current_character->width = char_bitmap_width;
        // current_character->height = char_bitmap_height;

        current_character->memory = stbtt_GetCodepointBitmap(&font, 0, stbtt_ScaleForPixelHeight(&font, size), alphabet[i],
                                                 &current_character->width, &current_character->height, 0, 0);
        current_character++;
    }
}

(在不同的文件中,在主更新和渲染函数中,每一帧我都调用这个函数)

void test_render_text(offscreen_buffer* buffer, font_buffer* font_bitmaps)
{
    int width = font_bitmaps->memory[0].width;
    int height = font_bitmaps->memory[0].height;

    unsigned char* dest_row = (unsigned char*)buffer->memory
    unsigned char* source = font_bitmaps->memory[42].memory;
    for (int y = 0; y < height; y++)
    {
        unsigned int* dest_pixel = (unsigned int*)dest_row;

        for (int x = 0; x < width; x++)
        {
            unsigned char alpha = *source;
            *dest_pixel = ((alpha << 24)
                          | (alpha << 16)
                          | (alpha << 8)
                          | (alpha << 0));

            dest_pixel++;
            source++;
        }

        dest_row += buffer->pitch;
    }
}

如果您想查看/编译完整的源代码,也可以在 github 上发布: https ://github.com/jackson-lenhart/loji

标签: cwinapibitmaptruetype

解决方案


推荐阅读