跳轉到內容

SDL (簡易直接媒體層) - 建立視窗

來自華夏公益教科書,開放書籍,為開放世界

在本節中,我們將演示如何建立和銷燬基本的 SDL 視窗。以下程式碼將建立一個名為“SDL 示例”的視窗,寬度為 800 畫素,高度為 600 畫素,並在螢幕上顯示 3000 毫秒。

#include <stdio.h> /* printf and fprintf */

#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#endif

/* Sets constants */
#define WIDTH 800
#define HEIGHT 600
#define DELAY 3000

int main (int argc, char **argv)
{
  /* Initialises data */
  SDL_Window *window = NULL;
  
  /*
  * Initialises the SDL video subsystem (as well as the events subsystem).
  * Returns 0 on success or a negative error code on failure using SDL_GetError().
  */
  if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    fprintf(stderr, "SDL failed to initialise: %s\n", SDL_GetError());
    return 1;
  }

  /* Creates a SDL window */
  window = SDL_CreateWindow("SDL Example", /* Title of the SDL window */
			    SDL_WINDOWPOS_UNDEFINED, /* Position x of the window */
			    SDL_WINDOWPOS_UNDEFINED, /* Position y of the window */
			    WIDTH, /* Width of the window in pixels */
			    HEIGHT, /* Height of the window in pixels */
			    0); /* Additional flag(s) */

  /* Checks if window has been created; if not, exits program */
  if (window == NULL) {
    fprintf(stderr, "SDL window failed to initialise: %s\n", SDL_GetError());
    return 1;
  }

  /* Pauses all SDL subsystems for a variable amount of milliseconds */
  SDL_Delay(DELAY);

  /* Frees memory */
  SDL_DestroyWindow(window);
  
  /* Shuts down all SDL subsystems */
  SDL_Quit(); 
  
  return 0;
}

您可以在 GitLab 倉庫 中下載本節的原始碼。所有原始碼儲存在 該組 中。

設定資料

[編輯 | 編輯原始碼]

為了建立視窗,我們需要指定它的高度和寬度。在本例中,我們使用宏定義全域性常量。我們將寬度設定為 800 畫素,高度設定為 600 畫素。

#define WIDTH 800
#define HEIGHT 600

在此程式中,我們將不得不暫停 SDL 子系統以使視窗保持開啟狀態。我們將延遲定義為 3000 毫秒。

#define DELAY 3000

在 C 中,最好先初始化變數,以便了解它們何時以及如何使用。在本例中,我們初始化一個名為 windowSDL_Window 指標。在 SDL 中,幾乎所有物件都初始化為指標。

SDL_Window *window = NULL;

建立視窗

[編輯 | 編輯原始碼]

為了建立視窗,我們需要使用 SDL_CreateWindow 函式並設定一些引數。

window = SDL_CreateWindow("SDL Example", /* Title of the SDL window */
			  SDL_WINDOWPOS_UNDEFINED, /* Position x of the window */
			  SDL_WINDOWPOS_UNDEFINED, /* Position y of the window */
			  WIDTH, /* Width of the window in pixels */
			  HEIGHT, /* Height of the window in pixels */
			  0); /* Additional flag(s) */

您可以在 SDL Wiki 中瞭解更多關於 SDL_CreateWindow 的資訊。

使用 SDL_Delay

[編輯 | 編輯原始碼]

在示例程式碼中,我們使用了 SDL_Delay 函式來暫停 SDL 子系統一段時間(以毫秒為單位),並允許視窗在開啟時顯示在螢幕上。在本例中,暫停由 DELAY 宏定義為 3000 毫秒。

SDL_Delay(DELAY);

您可以在 SDL Wiki 中瞭解更多關於 SDL_Delay 的資訊。

銷燬視窗

[編輯 | 編輯原始碼]

為了關閉視窗並釋放記憶體,我們必須銷燬視窗。銷燬 window 比建立它簡單得多。

SDL_DestroyWindow(window);

您可以在 SDL Wiki 中瞭解更多關於 SDL_DestroyWindow 的資訊。

華夏公益教科書