Skip to content

Instantly share code, notes, and snippets.

@newvertex
Last active January 14, 2022 22:36
Show Gist options
  • Save newvertex/effbbee95763ce739d9315c7e37f3133 to your computer and use it in GitHub Desktop.
Save newvertex/effbbee95763ce739d9315c7e37f3133 to your computer and use it in GitHub Desktop.
Render Persian RTL Text in SDL2 with SDL_ttf
SDL_Texture *renderText(const char *text, bool isUTF8, const char *fontPath, SDL_Color color, int fontSize, SDL_Renderer *renderer)
{
TTF_Font *font = TTF_OpenFont(fontPath, fontSize);
if (font == NULL)
{
//logErrorSDL("Failed to Open Font!");
return NULL;
}
SDL_Surface *surface;
if (isUTF8)
{
TTF_SetDirection(5); // HB_DIRECTION_RTL
TTF_SetScript(1098015074); // HB_SCRIPT_ARABIC
surface = TTF_RenderUTF8_Blended(font, text, color);
}
else
{
surface = TTF_RenderText_Blended(font, text, *color);
}
if (surface == NULL)
{
TTF_CloseFont(font);
//logErrorSDL("Failed to Render Text!");
return NULL;
}
TTF_CloseFont(font);
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture == NULL)
{
//logErrorSDL("Failed to Create Text Texture!");
}
SDL_FreeSurface(surface);
return texture;
}
TTF_SetDirection(5);  // [1]
TTF_SetScript(1098015074);  // [2]
surface = TTF_RenderUTF8_Blended(font, text, color);

Where I found the numbers:

[1]

HB_DIRECTION_RTL = 5;

direction: https://github.com/harfbuzz/harfbuzz/blob/8a69e0063936764cbd149985e0b57e1dc35935c2/src/hb-common.h#L222

typedef enum {
 HB_DIRECTION_INVALID = 0,
 HB_DIRECTION_LTR = 4,
 HB_DIRECTION_RTL,
 HB_DIRECTION_TTB,
 HB_DIRECTION_BTT
} hb_direction_t;

[2]

uint32_t script_code = ((uint32_t)((((uint32_t)('A')&0xFF)<<24)|(((uint32_t)('r')&0xFF)<<16)|(((uint32_t)('a')&0xFF)<<8)|((uint32_t)('b')&0xFF)));
printf("%d\n", script_code);

script tag: https://github.com/harfbuzz/harfbuzz/blob/8a69e0063936764cbd149985e0b57e1dc35935c2/src/hb-common.h#L500

HB_SCRIPT_ARABIC			= HB_TAG ('A','r','a','b'), /*1.1*/

calculate value of script tag: https://github.com/harfbuzz/harfbuzz/blob/8a69e0063936764cbd149985e0b57e1dc35935c2/src/hb-common.h#L159

#define HB_TAG(c1,c2,c3,c4) ((hb_tag_t)((((uint32_t)(c1)&0xFF)<<24)|(((uint32_t)(c2)&0xFF)<<16)|(((uint32_t)(c3)&0xFF)<<8)|((uint32_t)(c4)&0xFF)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment