简体   繁体   中英

How to load multiple images in SDL_image and SDL2?

I've been trying to load 2 images in a SDL window, like a player and an enemy, but SDL2_image loads only one image at a time here's my code :

#include<iostream>
#define SDL_MAIN_HANDLED
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
using namespace std;

SDL_Texture* load(SDL_Renderer* ren, const char* path, SDL_Rect rect)
{
    SDL_Texture* img = IMG_LoadTexture(ren, path);
    if (img == NULL)
        cout << SDL_GetError() << endl;
    SDL_RenderClear(ren);
    SDL_RenderCopy(ren, img, NULL, &rect);
    SDL_RenderPresent(ren);
    return img;
}

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);
    IMG_Init(IMG_INIT_PNG);

    SDL_Window* window = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 460, 380, SDL_WINDOW_RESIZABLE);

    SDL_Surface* icon = IMG_Load("sdl.png");
    SDL_SetWindowIcon(window, icon);

    SDL_Renderer* ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    SDL_Rect rect,r2;
    rect.x = 0; r2.x = 65;
    rect.y = 0; r2.y = 80;
    rect.w = 64; r2.w = 64;
    rect.h = 64; r2.h = 64;

    SDL_Texture* img = load(ren, "player.png", rect);
    SDL_Delay(2000);
    SDL_Texture* tex = load(ren, "enemy.png", r2);
    SDL_Event events; bool running = true;
    while (running == true)
    {
        if (SDL_PollEvent(&events))
        {
            if (events.type == SDL_QUIT)
            {
                running = false;
                break;
            }
        }
    }

    IMG_Quit();
    SDL_Quit();
    return 0;
}

I used SDL_Delay to demonstrate what happens it loads "player.png" first and then after 2 seconds, it loads "enemy.png" I wanted to load both at the same time but I couldn't

Please help!

解决了,这是由于 SDL_RenderClear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM