c++svgfontssdl-2sdl-image

How to render text from SVG pictures using SDL2?


I'm trying to render a picture from an SVG file, using the graphics rendering library SDL2.

Problem is, my SVG files have text tags (sometimes, with additional effects), like in this example:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="680.3215748031496" height="350.0788582677165">
    <text xmlns="http://www.w3.org/2000/svg" transform="translate(263.9375,206.64214) scale(0.8792,0.8792)" font-size="40" xml:space="preserve" fill="#8c3600" fill-rule="nonzero" stroke="#8c3600" stroke-width="3" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="Sans Serif" font-weight="normal" text-anchor="start" style="mix-blend-mode: normal">
        <tspan x="0" dy="0">Text</tspan>
    </text>
</svg>

My code to load SVG files is as follows:

uint8_t* textureData = /*Irrelevant function for me to load the file as a byte array*/
SDL_RWops *rw = SDL_RWFromMem(textureData, size);
SDL_Texture* tex = IMG_LoadTexture_RW(renderer, rw, true);

I'm using IMG_LoadTexture_RW to autodetect the image format, since I use many of them in my application. This gives me an SDL_Texture* to render.

But when rendering that SDL_Texture*, there's no text to be found on the picture rendered on screen.

I did link SDL_TTF and SDL_Image to my project, and looked for traces of this problem in the docs but couldn't find much.

I can't skip using SVG either, since those are provided on the fly by user-generated zip files that embed them.


Solution

  • As both SDL_image 3's code and SDL_image 2's code indicate, nanosvg is being used to parse and rasterize SVG files, which has no text support, and clearly doesn't plan to add it.

    As a result, the only ways to render text tags found in SVGs using SDL_image, as of SDL 3.2, are:

    If none of those solutions seem good to you, you can always try to work on a cleaner solution by implementing this directly into SDL_image and sending them a pull request so other developers can benefit from it, and to allow such a feature to be officially supported!