c++ - SDL_Image 不显示图像

标签 c++ sdl sdl-image

在修复了各种其他 SDL 错误之后,(包括 SDL 本身和 SDL_Image)我写了这段无错误的代码:

#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <string>

using namespace std;

#define null 0

SDL_Window *window = nullptr;
SDL_Renderer *renderer = nullptr;

SDL_Texture* LoadImage(string file)
{
    SDL_Texture *texture = nullptr;

    texture = IMG_LoadTexture(renderer, file.c_str());
    if (texture == nullptr)
        cout << "Failed to load image: " + file + IMG_GetError();
    return texture;
}

void ApplySurface(int x, int y, SDL_Texture *textureArgument, SDL_Renderer *rendererArgument)
{
    SDL_Rect pos;
    pos.x = x;
    pos.y = y;
    SDL_QueryTexture(textureArgument, null, null, &pos.w, &pos.h);
    SDL_RenderCopy(rendererArgument, textureArgument, null, &pos);
}

int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING))
        return 1;

    window = SDL_CreateWindow("ShitHappens", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    SDL_Texture *image = nullptr;
    image = LoadImage("image.png");

    SDL_RenderClear(renderer);

    int iW, iH;
    SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
    int x = 640 / 2 - iW / 2, y = 480 / 2 - iH / 2;

    ApplySurface(x, y, image, renderer);
    SDL_RenderPresent(renderer);

    SDL_Delay(2000);
    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    return 0;
}

仍然没有显示有问题的图像。我已经尝试用 SDL_LoadBMP() 图像替换函数并且它成功了,如果我通过当前代码加载 BMP 图像而不是 PNG 图像,它甚至可以工作。

最佳答案

如果在 Windows 上加载 BMP 文件而未加载 PNG 文件,则您遇到了 DLL 位置问题。要在 Windows 上正确加载 PNG,SDL_image 要求 libpng 和 zlib DLL 与可执行文件位于同一目录中。 Windows 版本的 SDL_image 使用 libpng 和 zlib 加载 PNG 文件,因此您必须将这些 DLL 放在正确的目录中。仅将 SDL_image DLL 与可执行文件放在同一目录中是不够的。

关于c++ - SDL_Image 不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994091/

相关文章:

c++ - &(*similarObject) 和similarObject 之间的区别?他们不一样吗?

c++ - 如果我有固定数量的相互独立的计算,多线程是否会显着提高性能?

c++ - SDL基本程序不工作但代码没问题

c++ - SDL_image/C++ OpenGL 程序 : IMG_Load() produces fuzzy images

c++ - SDL_image 无法使用 IMG_LoadTexture() 加载 .png 文件

c++ - 安卓NDK : Not picking up CPP includes

c++ - 没有映射值分配给键时调用 operator [] 的行为

c++ - 在 C++ 中更好地控制成员对象的构造

c++ - 在 C++ 中使用 y = mx + b 公式移动圆

c++ - SDL 错误 : Invalid Renderer on SDL_CreateTextureFromSurface