首页 > 其他分享 >SDL的初始化与注意事项

SDL的初始化与注意事项

时间:2022-11-21 16:37:47浏览次数:48  
标签:初始化 success gWindow printf 注意事项 SDL NULL gImageSurface

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

//主窗口
SDL_Window* gWindow = NULL;

//主窗口内含的主表面
SDL_Surface* gScreenSurface = NULL;

//图片表面
SDL_Surface* gImageSurface = NULL;


//初始化SDL并创建窗口
bool init()
{
    bool success = true;

    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf("SDL无法初始化! SDL_Error: %s\n", SDL_GetError());
        success = false;
    }
    else
    {
        gWindow = SDL_CreateWindow("Suya SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN);
        //gWindow = SDL_CreateWindow("Suya SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);

        if (gWindow == NULL)
        {
            printf("无法创建窗口! SDL_Error: %s\n", SDL_GetError());
            success = false;
        }
        else
        {
            //获取窗口表面
            gScreenSurface = SDL_GetWindowSurface(gWindow);
        }
    }

    return success;
}

//加载资源
bool loadMedia(char* file) {

    bool success = true;

    gImageSurface = SDL_LoadBMP(file);
    if (gImageSurface == NULL)
    {
        printf("无法加载图像 %s! SDL Error: %s\n", "hello.bmp", SDL_GetError());
        success = false;
    }

    return success;
}

//释放资源、关闭SDL
void close() {

    SDL_FreeSurface(gImageSurface);
    gImageSurface= NULL;

    SDL_DestroyWindow(gWindow);
    gWindow = NULL;

    SDL_Quit();
}

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

    if (!init()) {

        printf("SDL 初始化失败!\n");
    }
    else {

        if (!loadMedia(const_cast<char*>("hello.bmp"))) {

            printf("加载资源文件失败!\n");
        }
        else {

            //将图片表面绘制到主表面上
            SDL_BlitSurface(gImageSurface, NULL, gScreenSurface, NULL);

            //更新窗口,此函数是SDL_Flip()的迭代版本
            SDL_UpdateWindowSurface(gWindow);

            //事件循环
            SDL_Event e; 
            bool quit = false; 
            
            while (quit == false) { 

                while (SDL_PollEvent(&e)) { 

                    if (e.type == SDL_QUIT) 
                        quit = true; 
                } 
            }
        }
    }

    close();
    return 0;
}

 

在引入SDL后,入口函数必须是 int main(int argc, char* argv[]),类似void main()或其它形式的都会导致程序报错

 

此图为window,蓝色区域为gScreenSurface ,红框内为ImageSurface

SDL_Flip()已废弃,并由SDL_UpdateWindowSurface()替代

标签:初始化,success,gWindow,printf,注意事项,SDL,NULL,gImageSurface
From: https://www.cnblogs.com/anzf/p/16911819.html

相关文章