在修复了各种其他 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 图像,它甚至可以工作。