3

在 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...loop 的每个循环之后,我想在缓冲区中添加一行 - 在程序运行结束时应该有 8 行。在这种情况下,我在一个缓冲区上得到 4 个,在另一个缓冲区上得到 4 个。我也不想再次重绘前面的行,因此需要一个缓冲区:

屏幕一

屏幕 2

4

1 回答 1

8

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

#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;
}

输出如下:

在此处输入图像描述

于 2013-11-20T09:04:15.707 回答