我试着创建一个有纹理的矩形,但当我试图运行程序时,它只是进入黑屏:
#include <SDL2/SDL.h>
#include "dinoHeader.h"
int main(int argc, const char * argv[]) {
if(SDL_Init(SDL_INIT_EVERYTHING) < 0){
return 1;
}
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
SDL_Surface* surface = SDL_LoadBMP("./Images/smile.bmp");
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
SDL_Rect rect;
rect.w = 100;
rect.h = 100;
rect.x = (ScreenWidth / 2) - (rect.w / 2);
rect.y = (ScreenHeight / 2) - (rect.h / 2);
window = SDL_CreateWindow("Dino", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
game = true;
while (game) {
SDL_Event event;
while(SDL_PollEvent(&event)){
if(event.type == SDL_QUIT){
game = false;
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, &rect);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyTexture(texture);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
我用的是Xcode。
1条答案
按热度按时间tzcvj98z1#
在这几行中,你将
nullptr
传递给SDL_CreateTextureFromSurface
,因为渲染器还没有创建。在创建纹理时,你应该使用有效的工作渲染器-所以,首先创建渲染器,只有这样你才能使用它来创建纹理。如注解中所述,您应该检查返回值(在这种情况下,您的
texture
应该是nullptr
,因为纹理创建失败),如果它们不符合预期-使用SDL_GetError
检查SDL为您设置的错误消息。