TTF tells me that I have 0 width...

Started by
1 comment, last by nullsquared 17 years, 10 months ago

    Text has zero width
This is stdout.txt... I am using ttf to take a .ttf file and then make a bitmap font with it for use with my bitmap-font engine. The only bad part is that it fails with the above message... This is the code:

#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

void init() {
    SDL_Init(0);
    TTF_Init();
}

void deinit() {
    TTF_Quit();
    SDL_Quit();
}

int main(int argc, char *argv[]) {
    init();

    ifstream f("data.txt");
    string filename;
    int size, fr, fg, fb, br, bg, bb;
    f >> filename >> size >> fr >> fg >> fb >> br >> bg >> bb;

    TTF_Font *font = TTF_OpenFont((filename + ".ttf").c_str(), size);
    if (!font) {
        cout << TTF_GetError();
        return 1;
    }

    char ascii[256];
    for (unsigned i = 0; i < 256; i++)
        ascii = (char)i;

    SDL_Color foreground = {fr, fg, fb};
    SDL_Color background = {br, bg, bb};

    SDL_Surface *str = TTF_RenderText_Shaded(
        font,
        ascii,
        foreground,
        background
    );

    if (!str) {
        cout << TTF_GetError();
        return 1;
    }

    SDL_SaveBMP(str, (filename + ".bmp").c_str());

    SDL_FreeSurface(str);
    TTF_CloseFont(font);
    deinit();
}

Any ideas? I just hacked this together very quickly, but it should work... And yes, data.txt exists as follows:

    times 16 255 255 255 0 0 0
And again yes, times.ttf is in there too. THANKS!
Advertisement
The C string you passed to TTF_RenderText_Shaded() has zero width.

This is because you set the very first character in the string to zero.
for (unsigned i = 0; i < 256; i++)
ascii = (char)i;

When i =0, then
ascii[0] = (char)0;//This line will terminate the C -string,resulting in zero width.

Try this as a test.
char ascii[27];//space for 26 letters and the string terminator(0).
//Print out the lower case alphabet
for (unsigned i = 0; i < 26; i++)
ascii = (char)i+'a'; //string consisting of letters 'a' through 'z'

Make sure to NULL terminate C strings
ascii[26] = 0;//goes after the above example

For your purposes you can change the NULL terminate to a space
ascii = (char)(i==0)?' ':i;
or choose a range (SFont uses ascii 33-127)
ascii[95];
for(int i =0; i < 94;i++)
ascii = (char)(33+i);
ascii[94] = 0;
Good Luck.

[Edited by - Jack Sotac on June 14, 2006 4:53:17 PM]
0xa0000000
Oops, thanks! I hadn't use character arrays for so long now that I forgot '\0' terminates the string. Again, thanks (rat++).

This topic is closed to new replies.

Advertisement