SDL2 - 如何用一个缓冲区而不是两个缓冲区渲染?

时间:2013-11-12 17:20:07

标签: c sdl sdl-2

在SDL2中,我希望能够将更改绘制到一个缓冲区,而不是将整个图像重绘为两个不同的缓冲区,就像我的设置似乎正在做的那样。下面是一个非常快速的测试,显示了不需要的行为:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <SDL.h>

// Compile: gcc test.c -I/usr/local/include/SDL2 -L/usr/local/lib -lSDL2


void putPixel(SDL_Renderer *renderer, int x, int y)
{
    SDL_SetRenderDrawColor(renderer, 255,255,255,255);
    SDL_RenderDrawPoint(renderer, x, y);
}

int main(int argc, char* argv[]) {

    int width = 640;
    int height = 480;

    SDL_Window *window = SDL_CreateWindow("Test", 0,0,width,height, 0);
    if (window == NULL)
    {
        return -1;
    }
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if (renderer == NULL)
    {
        return -2;
    }

    SDL_SetRenderDrawBlendMode(renderer,SDL_BLENDMODE_BLEND);

    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);

    for(int x=0;x<8;x++)
    {
        for(int y=0;y<10;y++)
        {
            putPixel(renderer,40+x*10,50+y);
        }

        SDL_RenderPresent(renderer);
        sleep(1);
    }


    SDL_Quit();
    return 0;
}

此输出是两个交替的屏幕。它显然使用双缓冲区,这意味着我必须清除并重绘以获得我想要的输出。在for ...循环的每个循环之后,我想在缓冲区中添加一行 - 在程序运行结束时应该有8行。在这种情况下,我在一个缓冲区上有4个,在另一个上有4个。我不想再重绘前一行,因此需要一个缓冲区:

Screen 1

Screen 2

1 个答案:

答案 0 :(得分:7)

这使用纹理作为缓冲区,并在完成后将其复制到屏幕上。

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <SDL.h>

// Compile: gcc test.c -I/usr/local/include/SDL2 -L/usr/local/lib -lSDL2


void putPixel(SDL_Renderer *renderer, int x, int y)
{
    SDL_SetRenderDrawColor(renderer, 255,255,255,255);
    SDL_RenderDrawPoint(renderer, x, y);
}

int main(int argc, char* argv[]) {

    int width = 640;
    int height = 480;

    SDL_Window *window = SDL_CreateWindow("Test", 0,0,width,height, 0);
    if (window == NULL)
    {
        return -1;
    }
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);
    if (renderer == NULL)
    {
        return -2;
    }

    SDL_SetRenderDrawBlendMode(renderer,SDL_BLENDMODE_BLEND);

    /* Create texture for display */
    SDL_Texture *display = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);

    SDL_SetRenderTarget(renderer, display);

    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);

    for(int x=0;x<8;x++)
    {
        SDL_SetRenderTarget(renderer, display);

        for(int y=0;y<10;y++)
        {
            putPixel(renderer,40+x*10,50+y);
        }

        SDL_SetRenderTarget(renderer, NULL);
        SDL_RenderCopy(renderer, display, NULL, NULL);
        SDL_RenderPresent(renderer);
        sleep(1);
    }


    SDL_Quit();
    return 0;
}

这个输出如下:

enter image description here