我想使用 SDL_ttf 在可能复杂的图像上绘制文字,这样文字是不透明的,但不会绘制背景框;背景是透明的。这可能吗?这是我的尝试;我曾希望通过使 bgColor 透明我可以达到这个结果。但不,我的字体仍然被黑框包围。
(我知道这个答案,但在 14 岁的时候它看起来已经完全过时了。SDL2 中的情况是否变得更好了?)
void DrawText(int x, int y, const char* text, SDL_Color textColor, TTF_Font *font) {
int width, height;
SDL_Color bgColor = { 0, 0, 0, 0};
SDL_Surface* textSurface =
TTF_RenderText_Shaded(font, text, textColor, bgColor);
if( textSurface == NULL )
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
else {
//Create texture from surface pixels
SDL_Texture *mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
if( mTexture == NULL ) printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
else {
//Get image dimensions
width = textSurface->w;
height = textSurface->h;
}
//Get rid of old surface
SDL_FreeSurface( textSurface );
//Render to screen
int descent = TTF_FontDescent(gFont);
SDL_Rect renderQuad = { x, y-height-descent, width, height };
SDL_RenderCopy( gRenderer, mTexture, NULL, &renderQuad);
SDL_DestroyTexture(mTexture);
}
}
答案其实很简单。复制一些旧的示例,我使用 TTF_RenderText_Shaded 绘制文本,它会生成一个带有调色板的 8 位表面来表示颜色。当我们的比特数较少时,这种技术很重要,但在我看来已经过时了,目前很少有用。它需要一个明确的背景颜色,当位块传输时,它会覆盖之前的任何内容。
TTF_RenderText_Blished 正是我想要的。它生成一个背景完全透明的 ARGB 表面,因此当它被传输到目标上时,它只绘制文字而不绘制其他内容。减去设置的东西,这是我的工作代码:
void DrawText(int x, int y, const char* text, SDL_Color fg) {
int width, height;
if (strlen(text) == 0) return;
SDL_Color bgColor = { 0xff, 0xff, 0xff, 0xff};
SDL_Surface* textSurface = TTF_RenderText_Blended(gFont, text, fg);
if( textSurface == NULL )
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
else {
//Create texture from surface pixels
SDL_Texture *mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
if( mTexture == NULL ) {
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
} else {
//Get image dimensions
width = textSurface->w;
height = textSurface->h;
}
//Get rid of old surface
SDL_FreeSurface( textSurface );
//Render to screen
int descent = TTF_FontDescent(gFont);
printf("height: %d descent:%d\n", height, descent);
SDL_Rect renderQuad = { x, y-height-descent, width, height };
SDL_RenderCopy( gRenderer, mTexture, NULL, &renderQuad);
SDL_DestroyTexture(mTexture);
}
}
void TextTest() {
SDL_Color c1 = {0xff, 0xff, 0x00, 0x00};
SDL_Color c2 = {0xff, 0x00, 0xff, 0x00};
DrawText(50, 50, "hello", c1);
DrawText(60, 55, "goodbye", c2);
}
其输出: