首页 > 解决方案 > C 在屏幕上显示字体图像素

问题描述

我目前正在学习字体图和位图,我希望能够获取这个字体图,并将其以像素为单位输出到屏幕上。

unsigned char glyph_a[][8] = 
{
  {0x00, 0x00, 0x3c, 0x02, 0x3e, 0x42, 0x3e, 0x00},
}

我试图为此使用的功能是

void draw_Glyph(char *glyph_a)
{
 int x, y;
 int set;
 for (x=0; x < 8; x++)
 {
  for (y=0; y < 8; y++)
  {
    set = glyph_a[x] & 1 << y;
  }
 }
}

SDL 提供了一个名为 SDL_RenderDrawPoint 的函数,该函数接受渲染器以及位置的 x 和 y 值。

C 有一个名为 putpixel() 的图形库,它也只接受像素的 x 和 y 值,并且还接受颜色作为最后一个参数。

我不确定我应该使用什么函数来专门将其输出到像素。任何建议将不胜感激。

标签: cfontssdl

解决方案


您可以将您的draw_Glyph()功能更改为:

struct Color {
    Uint8 r, g, b, a;
}

Color create_Color(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
    Color clr;
    clr.r = r;
    clr.g = g;
    clr.b = b;
    clr.a = a;
    return clr;
}

void draw_Glyph(SDL_Renderer* renderer, /* Renderer instance to draw the glyph on */
                char* glyph,            /* The glyph to display */
                Color on_color,         /* Color to use for 'on' bits in the glyph */
                Color off_color         /* Color to use for 'off' bits in the glyph */
                )
{
    for (int y = 0; y < 8; y++)
        for (int x = 0; x < 8; x++) {
            // Check if the bit is 'on' or 'off' and set the color of the pixel accordingly
            if (glyph[y] & (1 << (7 - x)))
                SDL_SetRenderDrawColor(renderer, on_color.r, on_color.g, on_color.b, on_color.a);
            else
                SDL_SetRenderDrawColor(renderer, off_color.r, off_color.g, off_color.b, off_color.a);
            // Draw the point where it is needed
            SDL_RenderDrawPoint(renderer, x, y);
        }
}

然后你可以像这样使用它:

const Color on_clr = create_Color(255, 255, 255, 255); // WHITE
const Color off_clr = create_Color(0, 0, 0, 255);      // BLACK
draw_Glyph(renderer, *glyph_a, on_clr, off_clr);

请注意,您需要传递一个SDL_Renderer*实例才能使用它。

SDL_Renderer您可以在SDL 的网站上找到有关如何创建的最小示例。


推荐阅读