英文:
Render Text in SDL using C#
问题
我正在使用SDL来使用C#渲染图形,如线条和像素。我还需要在屏幕上显示一些文本。我在互联网上没有找到关于这个主题的任何资源。我大部分的代码是从C++翻译而来的。现在我需要渲染文本,但由于C#中似乎没有可用的类,我无法将其C++实现翻译成C#。
我找到了这个很棒的C++实现用于渲染文本:https://stackoverflow.com/a/22889483/574917
我需要知道如何在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.
答案1
得分: 3
SDL2-CS是用于SDL和TTF的良好包装器:
https://github.com/flibitijibibo/SDL2-CS
您提供的实现可以像这样实现:
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, "在这里放置您的文本", White);
// 现在您可以将其转换为纹理
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);
}
请注意,该库使用nint
来表示指针,而不需要unsafe
关键字。
如果您正在寻找具有TTF支持的不同SDL库,则sdlsharp(https://github.com/plunch/sdlsharp)是一个不错的选择。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论