Search code examples
cfontssdl

C display font map pixels on screen


I'm currently learning about fontmaps and bitmaps, I'd like to be able to take this fontmap, and output it to the screen in pixels.

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

The function I'm trying to use for this is

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 provides a function called SDL_RenderDrawPoint which takes the renderer, and an x and y value for location.

C has a graphics library for something called putpixel() where it also just takes the x and y values of the pixel, and also takes a color as the last argument.

I'm not sure what function I should be using to output this to pixels specifically. Any advice would be greatly appreciated.


Solution

  • You can change your draw_Glyph() function to this:

    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);
            }
    }
    

    Then you can use it like this:

    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);
    

    Do note that you need to pass an SDL_Renderer* instance in order to use it.

    You can find a minimal example on how to create an SDL_Renderer on SDL's website.