如何在SDL2中使用SDL2_gfx绘制纹理然后渲染?

时间:2016-06-06 04:01:26

标签: c graphics sdl sdl-2

我想实现一个类似MS-Paint的程序(虽然我的实际程序会比这更多),可以用鼠标绘制。

我正在使用SDL2SDL2_gfx

我希望保留一个SDL_Texture,用户可以在不清除的情况下连续进行绘图(除非用户要求)。

然后不断将SDL_Texture更新到屏幕上。

我的问题具体是如何在SDL2_gfx primitives上绘制SDL_Texture并将其复制到渲染器。任何与使用纹理完全不同的方式也适用于我,但必须使用SDL2。

以下是我的代码中最小的可运行提取:

#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <SDL2/SDL.h>
#include <SDL2_gfxPrimitives.h>

#define WIDTH (320)
#define HEIGHT (240)

SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_RendererInfo rendererInfo;
SDL_Texture* texture = NULL;
SDL_Event event;
Sint16 cx = WIDTH/2, cy = HEIGHT/2;
uint8_t quit = 0;

void init()
{
    SDL_Init(SDL_INIT_VIDEO);
    SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, SDL_WINDOW_OPENGL, &window, &renderer);
    texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, WIDTH, HEIGHT); // create texture to draw on to
    // SDL_SetRenderTarget(renderer, texture); // this one I have removed
}

void draw()
{
    pixelRGBA(renderer, cx, cy, 0xff, 0xff, 0x00, 0xff); // draw a pixel here, or whatever cx and cy are mouse position
    // what I want is to draw on to the texture, and not directly on the screen buffer
}

void render()
{
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // set clear color
    SDL_RenderClear(renderer); // clear the buffer
    SDL_RenderCopy(renderer, texture, NULL, NULL); // now copy the drawn texture to the buffer
    SDL_RenderPresent(renderer); // now update window
}

int main(int argc, char* argv[])
{
    int p;
    init();
    while(!quit)
    {
        SDL_PumpEvents();
        p = SDL_PollEvent(&event);
        if(p>0)
        {
            if(event.type==SDL_QUIT) quit = 1;
            else
            {
                // here other things are there to handle the mouse positions etc for drawing exactly what the user wants
                // ...
                draw();
                render();
            }
        }
    }
    SDL_Quit();
    return 0;
}

提前致谢。

0 个答案:

没有答案