SDL 2 BMP Blitting

时间:2015-03-11 01:43:55

标签: c++ sdl blit

我目前正在学习如何使用SDL 2.使用Lazy Foo' SDL2教程,显示为here,我创建了一个脚本,在关闭程序之前应该显示图像2秒。这是脚本:

#include <SDL.h>
#include <stdio.h>

//Screen dimensions
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

SDL_Window* window = NULL;

SDL_Surface* screenSurface = NULL;

SDL_Surface* surfaceImage = NULL;

bool init();

bool loadMedia();

void close();

bool init()
{
    bool success = true;
    //initializes
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    }
    else{
    //creates the window
        window = SDL_CreateWindow("Testing!", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if( window = NULL )
        {
            printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            screenSurface = SDL_GetWindowSurface(window);
        }
    }

    return success;

}

bool loadMedia()
{
    bool success = true;
    surfaceImage = SDL_LoadBMP( "test.bmp" );
    if(surfaceImage = NULL)
    {
        printf(SDL_GetError());
        success = false;
    }

    return success;
}

void close()
{
    SDL_DestroyWindow(window);
    window = NULL;
    SDL_Quit();
}

int main( int argc, char* args[] )
{
    if(!init())
    {
        printf( "Failed to initialize!\n" );
    }
    else{
        SDL_FillRect(screenSurface, NULL, ( screenSurface->format, 0xFF, 0xFF, 0xFF ));
        if(!loadMedia())
        {
            printf(SDL_GetError());
        }
        else{

            SDL_BlitSurface(surfaceImage, NULL, screenSurface, NULL);
            SDL_UpdateWindowSurface(window);
        }

        SDL_Delay(2000);
        close();
        return 0;
    }
    return 0;
}

但是,图像未显示。没有出现错误,程序运行得如此,除了图像不存在。我将bmp文件放在与vcproj文件相同的目录中。代码有什么问题?

1 个答案:

答案 0 :(得分:2)

修复两行代码:

if(window = NULL)更改为if(window == NULL)

if(surfaceImage = NULL)if(surfaceImage == NULL)

这是一个非常常见的错误 - 你几乎总是指第二个错误,但第一个错误是有效的,尽管它意味着非常不同。避免在未来犯同样错误的策略是养成改变if中操作数顺序的习惯:

if(NULL == window)有效,相当于if(window == NULL),但if(NULL = window)是一个编译器错误,因此如果你做错了,你会立即被告知错误。