0

我想知道如何使用 IMG_Load(); 处理多个图像 我是否总是必须为每个图像创建一个表面?或者我必须创建一些循环,只使用这个表面来创建纹理?

SDL_Surface* surface = IMG_Load("resources/hello.png");
SDL_Texture* tex = SDL_CreateTextureFromSurface(rend, surface);

这是代码:

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

int main(void)
{
    if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0)
    {
        printf("error initializing SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_Window* win = SDL_CreateWindow("Hello, SDL2!",
                                       SDL_WINDOWPOS_CENTERED,
                                       SDL_WINDOWPOS_CENTERED,
                                       640, 480, 0);
    if (!win)
    {
        printf("error creating window: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    Uint32 render_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
    SDL_Renderer* rend = SDL_CreateRenderer(win, -1, render_flags);
    if (!rend)
    {
      printf("error creating renderer: %s\n", SDL_GetError());
      SDL_DestroyWindow(win);
      SDL_Quit();
      return 1;
    }

    SDL_Surface* surface = IMG_Load("resources/hello.png");
    if (!surface)
    {
        printf("error creating surface\n");
        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(win);
        SDL_Quit();
        return 1;
    }
    SDL_Texture* tex = SDL_CreateTextureFromSurface(rend, surface);
    SDL_FreeSurface(surface);
    if (!tex)
    {
        printf("error creating texture: %s\n", SDL_GetError());
        SDL_DestroyRenderer(rend);
        SDL_DestroyWindow(win);
        SDL_Quit();
        return 1;
    }

    SDL_RenderClear(rend);

    SDL_RenderCopy(rend, tex, NULL, NULL);
    SDL_RenderPresent(rend);

    SDL_Delay(5000);
    
    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(rend);
    SDL_DestroyWindow(win);
    SDL_Quit();
    return 0;
}
4

1 回答 1

0

当我有很多图像要加载时,我通常做的是创建一个vectororarray类型SDL_Texture*,它是一个类的成员,并使用 for 循环设置它,加载图像并附加它们

于 2020-11-19T17:53:20.243 回答