我有一個 C 專案,我最初試圖在螢屏上顯示 PNG 影像。
這是我的代碼。
渲染視窗.hpp
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
class RenderWindow
{
public:
RenderWindow(const char *p_title, int p_width, int p_height);
void render();
void cleanUp();
private:
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Surface *image = IMG_Load("~/SDL2_Game/images/Green_Tile.png");
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image);
};
渲染視窗.cpp
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include "RenderWindow.hpp"
RenderWindow::RenderWindow(const char* p_title, int p_w, int p_h):window(NULL), renderer(NULL)
{
window = SDL_CreateWindow(p_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, p_w, p_h, SDL_WINDOW_SHOWN);
if (window == NULL) std::cout << "Window failed to init: " << SDL_GetError() << std::endl;
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
}
void RenderWindow::render(){
SDL_RenderClear(renderer);
//SDL_Rect dstrect = { 5, 5, 320, 240 };
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
void RenderWindow::cleanUp(){
SDL_DestroyTexture(texture);
SDL_FreeSurface(image);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
}
主檔案
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include "RenderWindow.hpp"
int main(int argc, char** argv){
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cout << "Problem with initialization. " << SDL_GetError() << std::endl;
}
else {
std::cout << "Initialization success!" <<std::endl;
}
if (!IMG_Init(IMG_INIT_PNG)){
std::cout << "Problem with Image initialization " <<SDL_GetError() << std::endl;
}
RenderWindow win("RPG_Game_v_1.0", 800, 600);
win.render();
bool gameRunning = true;
SDL_Event event;
while(gameRunning){
while(SDL_PollEvent(&event)){
if (event.type == SDL_QUIT) gameRunning = false;
}
}
win.cleanUp();
IMG_Quit();
SDL_Quit();
return 0;
}
我在一臺Linux機器上。
我編譯這個
g -g -o game ./*.cpp -lSDL2main -lSDL2 -lSDL2_image
只顯示一個視窗。沒有影像。我嘗試使用 SDL_BlitSurface() 重構我的代碼,它確實顯示了 PNG 影像。但是為什么這段代碼不起作用?是因為我使用的是 SDL_Texture* 而我當前的系統沒有獨立顯卡嗎?
uj5u.com熱心網友回復:
我認為呼叫SDL_CreateTextureFromSurface失敗是因為它在SDL_CreateWindowand之前被呼叫SDL_CreateRenderer,從而初始化texture為NULL.
請將texture(and image) 的初始化移到 and 之后window進行renderer初始化。
要進一步幫助解決此類問題,請檢查 SDL 函式的結果是否為 !=NULL并列印SDL_GetError()以獲取有關問題所在的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440074.html
標籤:C
