Farid-ur-Rahman
Farid-ur-Rahman

Reputation: 1869

Render Text in SDL using C#

I am using SDL to render graphics like lines and pixels using C#. I have to display some text on screen as well. I haven't found any resource on this topic on the internet. Most of the code that I wrote is translated from C++. Now I need to render text and I am not able to translate its C++ implementation into C# since the classes used are not seem to be available in C#.

I have found this great C++ implementation for rendering text: https://stackoverflow.com/a/22889483/574917

I need to know how to do this in C#.

Code sample is highly appreciated.

Upvotes: 0

Views: 878

Answers (1)

Ma_rv
Ma_rv

Reputation: 223

SDL2-CS is a good wrapper for SDL with TTF:
https://github.com/flibitijibibo/SDL2-CS

The implementation you gave would be implemented like this:

static void SdlWithSDL2CS(nint renderer)
{
    nint Sans = SDL_ttf.TTF_OpenFont("Sans.ttf", 24);

    SDL_Color White = new();
    White.r = White.g = White.b = White.a = 255;

    nint surfaceMessage = SDL_ttf.TTF_RenderText_Solid(Sans, "put your text here", White);

    // now you can convert it into a texture
    nint Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);

    SDL_Rect Message_rect;
    Message_rect.x = 0;
    Message_rect.y = 0;
    Message_rect.w = 100;
    Message_rect.h = 100;

    SDL_RenderCopy(renderer, Message, (nint)null, ref Message_rect);

    SDL_FreeSurface(surfaceMessage);
    SDL_DestroyTexture(Message);
}

Note that instead of struct* the library uses nint to represent pointers which won't require the unsafe keyword.

If you're looking for a different SDL library with TTF support, then sdlsharp (https://github.com/plunch/sdlsharp) is a good alternative.

Upvotes: 3

Related Questions