SDL (簡單直接媒體層) - 渲染表面
外觀
在本節中,我們將修改程式碼以使用 SDL_ConvertSurface 最佳化 SDL_Surface 的 blitting,並使用 SDL_BlitScaled 將影像拉伸到全屏。
您可以在此 GitLab 倉庫 中下載本節的原始碼。所有原始碼都儲存在 此組 中。
我們可以最佳化 SDL_Surface 以進行 blitting,這反過來又會提高效能。SDL_ConvertSurface 用於最佳化影像以實現更快的重複 blitting。這是透過轉換原始影像並將結果儲存為新的表面來實現的。
我們將使用以下程式碼更新我們的 wb_loadImage 函式。
/* Set temporary SDL_Surface */
SDL_Surface *temp = NULL;
/* Load the image from its file path to a SDL_Surface */
temp = IMG_Load(WB_IMAGE_PATH);
if (temp == NULL) {
fprintf(stderr, "WikiBook failed to load image: %s\n", IMG_GetError());
return -1;
}
/* Optimise SDL_Surface for blitting */
wb->image = SDL_ConvertSurface(temp, wb->screen->format, 0);
/* Destroy temporary SDL_Surface */
SDL_FreeSurface(temp);
請記住使用相應的函式銷燬 SDL 物件指標,在本例中為 SDL_FreeSurface。
我們將使用 SDL_BlitScaled 替換 SDL_BlitSurface。我們將編寫一個靜態(因此是私有的)函式,該函式將表面渲染到全屏。
/* Maximise surface to full screen */
static int setSurfaceFullScreen(SDL_Surface *surface, SDL_Surface *screen) {
/* Create SDL_Rect to full screen */
SDL_Rect rt = { 0, 0, WB_WIDTH, WB_HEIGHT };
/* Blit SDL_Surface to the size of SDL_Rect */
if (SDL_BlitScaled(surface, NULL, screen, &rt) < 0) {
fprintf(stderr, "Failed to set surface to full screen: %s\n", SDL_GetError());
return -1;
}
return 0;
}
我們將需要使用整個視窗的大小初始化並宣告一個 SDL_Rect,並使用該 SDL_Rect 的尺寸進行表面 blitting。
我們在 wb_loadImage 中替換 blitting 函式
/* Blit SDL_Surface to full screen */
if (setSurfaceFullScreen(wb->image, wb->screen) < 0) {
return -1;
}
您會注意到我們沒有宣告 SDL_Rect 指標,它與 SDL_Surface 等相比是一個相對較小的結構,因此我們不必為它動態分配記憶體。