stb_truetype.h和SDL2更改字体颜色

时间:2019-05-23 22:28:19

标签: c sdl-2 true-type-fonts

我正在使用stb_truetype.h和SDL2呈现文本。有没有简单的方法来更改字体颜色?这就是我所拥有的(文本为char *):

while (*text) {
    if (*text >= 32 && *text < 128) {
      stbtt_aligned_quad q;
      stbtt_GetBakedQuad(font->cdata, 512, 512, *text - 32, &x, &y, &q, 1);
      SDL_Rect src_rect = {.x = (int)512 * q.s0 - 1,
                           .y = (int)512 * (q.t0) - 1,
                           .w = (int)512 * (q.s1 - q.s0) + 1,
                           .h = (int)512 * (q.t1 - q.t0) + 1};
      SDL_Rect dst_rect = {
          .x = q.x0, .y = q.y0, .w = q.x1 - q.x0, .h = q.y1 - q.y0};


      // Has no effect because I am just grabbing a rect from the font data.
      SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
      // Always renders the font white.
      SDL_RenderCopy(renderer, font->texture, &src_rect, &dst_rect);
    }
    ++text;
}

我希望能够以不同的颜色呈现字体。现在,字体总是白色。

1 个答案:

答案 0 :(得分:0)

找到了一种使用SDL_SetTextureColorMod的方法:(https://wiki.libsdl.org/SDL_SetTextureColorMod

SDL_SetTextureColorMod(font->texture, 255, 0, 0);

例如将字体变成红色。

我使用此代码的原始代码:

while (*text) {
    if (*text >= 32 && *text < 128) {
      stbtt_aligned_quad q;
      stbtt_GetBakedQuad(font->cdata, 512, 512, *text - 32, &x, &y, &q, 1);
      SDL_Rect src_rect = {.x = (int)512 * q.s0 - 1,
                           .y = (int)512 * (q.t0) - 1,
                           .w = (int)512 * (q.s1 - q.s0) + 1,
                           .h = (int)512 * (q.t1 - q.t0) + 1};
      SDL_Rect dst_rect = {
          .x = q.x0, .y = q.y0, .w = q.x1 - q.x0, .h = q.y1 - q.y0};

      // set the font texture to display red.
      SDL_SetTextureColorMod(font->texture, 255, 0, 0);
      SDL_RenderCopy(renderer, font->texture, &src_rect, &dst_rect);
    }
    ++text;
}