gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:14:09 26 4
gpt4 key购买 nike

在 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 个。我也不想重新绘制前面的行,因此需要一个缓冲区:

Screen 1

Screen 2

最佳答案

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

#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

关于c - SDL2 - 如何使用一个缓冲区而不是两个进行渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com