lafferjm
lafferjm

Reputation: 194

SDL image does not display

I am currently trying to create a button class that looks as follows.

void Button::apply_image(std::string path) {

    SDL_Surface* loaded_image = NULL;
    loaded_image = IMG_Load(path.c_str());
    m_button_image = SDL_DisplayFormat(loaded_image);
    SDL_FreeSurface(loaded_image);

}

void Button::show(SDL_Surface* screen) {
    SDL_BlitSurface(m_button_image, NULL, screen, &m_box);
}

When using the class, I do the following:

Button button1(0,0,50,50);
button1.apply_image("images/cards/1.png");

SDL_Surface* screen = NULL;

screen = SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);
SDL_WM_SetCaption("House Of Cards", NULL);

button1.show(screen);
SDL_Flip(screen);

My problem is, the image is not displayed when I use SDL_DisplayFormat(loaded_image); But when I get rid of that line and the SDL_FreeSurface(loaded_image);. I then change loaded_image = IMG_load(path.c_str()); to m_button_image = IMG_Load(path.c_str()); the image will show up. Am I doing something wrong, because the path is obviously correct, because the image will show when I don't call DisplayFormat(). Through the use of gdb, m_button_image is NULL and I don't understand why it is, because gdb also shows that loaded_image points to an SDL_Surface*.

Upvotes: 2

Views: 457

Answers (2)

lafferjm
lafferjm

Reputation: 194

So I figured out what the problem was. I was calling SDL_DisplayFormat before I had initialized a screen. Because I had the functions in the wrong order, SDL_DisplayFormat did not have a surface to convert the image to.

Upvotes: 1

Gareth Francis
Gareth Francis

Reputation: 11

from http://sdl.beuc.net/sdl.wiki/SDL_DisplayFormat : 'If the conversion fails or runs out of memory, it returns NULL'

So it looks like the call to SDL_DisplayFormat is failing for some reason, it would probably be useful to do a check for m_button_image==NULL after the call to SDL_DisplayFormat, and if it is NULL to use SDL_GetError() to see what the error was

If that doesn't help then i'm not sure what would, though you could do a slower conversion by blitting the un-converted image to a display formatted surface, and using that as the image (pretty much the same but a bit more convoluted, would really just avoid the call to SDL_DisplayFormat)

Upvotes: 0

Related Questions