【问题标题】:SDL 2 BMP BlittingSDL 2 BMP 位图
【发布时间】:2015-03-11 10:00:19
【问题描述】:

我目前正在学习如何使用 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 文件放在同一目录中。代码有什么问题?

【问题讨论】:

    标签: c++ sdl blit


    【解决方案1】:

    修复两行代码:

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

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

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

    if(NULL == window) 有效并且等效于if(window == NULL),但if(NULL = window) 是编译器错误,所以如果你犯了错误,你会立即得到提示。

    【讨论】:

    • 哦,是的,我忘了 == 是一个东西。自从我上次编程以来已经有一段时间了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-11-14
    • 2017-09-11
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    相关资源
    最近更新 更多