gpt4 book ai didi

c - 如何在 SDL2 中渲染文本?

转载 作者:太空狗 更新时间:2023-10-29 16:21:17 25 4
gpt4 key购买 nike

我正在使用 SDL_WindowSDL_Renderer

是否可以将 SDL_TTFSDL_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);

我试着逐行解释代码,你在那里看不到任何窗口,因为我已经假设你知道如何初始化渲染器,这让我知道你也知道如何初始化窗口,那么您所需要的只是关于如何初始化纹理的想法。

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

关于c - 如何在 SDL2 中渲染文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com