SDL2 SLD_RenderCopy不显示任何内容

时间:2016-12-28 10:20:49

标签: c++ sdl

我使用SDL2来学习如何制作一个简单的2D平台。 我开始阅读SDL游戏开发和Lazy Foo的教程,我能够打开一个窗口并在一个表面上绘制并在窗口上显示该表面(就像它的表面一样)在遗留SDL中完成,但如果我尝试使用渲染器功能对硬件加速进行同样的操作,它就不会显示任何东西! 我在Windows 10上运行,当我启动应用程序时,它只显示空窗口。我试图打印一些调试行,似乎打开位图,创建纹理,但是当我打印矩形的尺寸时,我得到的是QueryTexture,它返回0和0!

//Game.cpp:
#include <SDL.h>
#include <SDL_image.h>
#include "Game.h"
#include <iostream>

bool Game::init(const char *title,int x,int y,int width,int height,int flags)
{
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
        return false;
    m_pWindow = SDL_CreateWindow(title,x,y,width,height,flags);
    if (m_pWindow == NULL)
        return false;
    m_pRenderer = SDL_CreateRenderer(m_pWindow,-1,0);
    if (m_pRenderer == NULL)
        return false;
    SDL_SetRenderDrawColor(m_pRenderer,0,0,0,255);
    return true;
}

void Game::handle_events()
{
    SDL_Event event;
    while (SDL_PollEvent(&event) != 0)
    {
        switch (event.type)
        {
            case SDL_QUIT:
                m_bRunning = false;
                break;
            default:
                break;
        }
    }
}

void Game::render()
{
    SDL_RenderClear(m_pRenderer);
    SDL_RenderCopy(m_pRenderer,m_pTexture,&m_sourceRectangle,&m_destinationRectangle);
    SDL_RenderPresent(m_pRenderer);
}

void Game::clean()
{
    SDL_DestroyWindow(m_pWindow);
    SDL_DestroyRenderer(m_pRenderer);
    SDL_Quit();
}

bool Game::loadImage()
{
    SDL_Surface *surface = SDL_LoadBMP("logo.bmp");
    if (surface == NULL)
        return false;
    SDL_Texture *texture =  SDL_CreateTextureFromSurface(m_pRenderer,surface);
    if (texture == NULL)
        return false;
    SDL_FreeSurface(surface);
    SDL_QueryTexture(m_pTexture,NULL,NULL,&m_sourceRectangle.w,&m_sourceRectangle.h);
    m_destinationRectangle.x = m_sourceRectangle.x = 0;
    m_destinationRectangle.y = m_sourceRectangle.y = 0;
    m_destinationRectangle.w = m_sourceRectangle.w;
    m_destinationRectangle.h = m_sourceRectangle.h;
    return true;
}



// main.cpp:
#include <SDL.h>
#include "Game.h"
#include <iostream>
#include <Windows.h>

Game *g_game = NULL;

int main(int argc,char **argv)
{
    AllocConsole(); 
    freopen("CON","w", stdout);

    g_game = new Game();
    if (g_game->init("my 2D platform game!",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,800,600,SDL_WINDOW_SHOWN) != true)
        return 1;
    if (g_game->loadImage() != true)
        return 2;
    g_game->render();

    while (g_game->running())
    {
        g_game->handle_events();
        g_game->update();
    }

    g_game->clean();

    return 0;
}

1 个答案:

答案 0 :(得分:2)

问题是您没有正确分配纹理 Game::loadImage()函数。在行

SDL_Texture *texture = SDL_CreateTextureFromSurface(m_pRenderer,surface);

将创建的纹理分配给本地指针变量 在功能结束时超出范围。相反,你需要努力 类变量的纹理:

m_pTexture = SDL_CreateTextureFromSurface(m_pRenderer,surface);

作为一个注释,您没有充分利用C ++功能 管理资源。我建议你投入一些时间 了解推荐的做法,例如来自 C++ Core Guidelines