如何在SDL2中渲染文本?

2024-02-02

我正在使用一个SDL_Window and SDL_Renderer.

是否可以使用SDL_TTF with SDL_Render/SDL_Window?如果是这样,怎么办?


是的,这是可能的,鉴于您有一个渲染器和一个窗口,加上您实际上没有任何关于涉足表面的想法,那么您可能想要介意创建纹理,这里是一个示例代码

//this opens a font style and sets a size
TTF_Font* Sans = TTF_OpenFont("Sans.ttf", 24);

// this is the color in rgb format,
// maxing out all would give you the color white,
// and it will be your text's color
SDL_Color White = {255, 255, 255};

// as TTF_RenderText_Solid could only be used on
// SDL_Surface then you have to create the surface first
SDL_Surface* surfaceMessage =
    TTF_RenderText_Solid(Sans, "put your text here", White); 

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

SDL_Rect Message_rect; //create a rect
Message_rect.x = 0;  //controls the rect's x coordinate 
Message_rect.y = 0; // controls the rect's y coordinte
Message_rect.w = 100; // controls the width of the rect
Message_rect.h = 100; // controls the height of the rect

// (0,0) is on the top left of the window/screen,
// think a rect as the text's box,
// that way it would be very simple to understand

// Now since it's a texture, you have to put RenderCopy
// in your game loop area, the area where the whole code executes

// you put the renderer's name first, the Message,
// the crop size (you can ignore this if you don't want
// to dabble with cropping), and the rect which is the size
// and coordinate of your texture
SDL_RenderCopy(renderer, Message, NULL, &Message_rect);

// Don't forget to free your surface and texture
SDL_FreeSurface(surfaceMessage);
SDL_DestroyTexture(Message);

我试图逐行解释代码,你在那里看不到任何窗口,因为我已经假设你知道如何初始化渲染器,这会让我知道你也知道如何初始化窗口,然后你就可以了need 是关于如何初始化纹理的想法。

这里有一个小问题,你的窗户打开了吗?它是黑色的吗?如果是这样,那么我的想法是正确的,如果不是,那么您可以问我,我可以更改此代码以实现由渲染器和窗口组成的整个部分。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在SDL2中渲染文本? 的相关文章

随机推荐