【问题标题】:Drawing pixels on the screen with SDL in C在 C 中使用 SDL 在屏幕上绘制像素
【发布时间】:2013-09-21 19:08:48
【问题描述】:

我有一个项目,我需要使用 SDL 在屏幕上绘制像素。已向我提供了一些代码:

int render_screen(SDL_Surface* screen)
{
  pixel pixel_white;
  pixel_white.r = (Uint8)0xff;
  pixel_white.g = (Uint8)0xff;
  pixel_white.b = (Uint8)0xff;
  pixel_white.alpha = (Uint8)128;


  SDL_LockSurface(screen);
  /*do your rendering here*/


  /*----------------------*/
  SDL_UnlockSurface(screen);

  /*flip buffers*/
  SDL_Flip(screen);
  clear_screen(screen);

  return 0;
}

还有这个功能:

void put_pixel(SDL_Surface* screen,int x,int y,pixel* p)
{
  Uint32* p_screen = (Uint32*)screen->pixels;
  p_screen += y*screen->w+x;
  *p_screen = SDL_MapRGBA(screen->format,p->r,p->g,p->b,p->alpha);  
}

这段代码中有很多我不明白的地方。首先,我假设我应该从 render_screen 函数中调用函数 put_pixel ,但是使用什么参数? put_pixel(SDL_Surface* screen,int x,int y,pixel* p) 行似乎很复杂。如果 x 和 y 是函数绘制参数,为什么它们会在函数 indata 中声明?我应该使用命令 put_pixel(something,x,y,something2) 调用 put_pixel。如果我使用 x=56 和 y=567,当在 parentesis 中声明时它们不是重置为 0 吗?我应该添加什么东西来让它工作?

【问题讨论】:

  • 我认为这里真正的问题是你是 C 的初学者。C 一开始是一门具有挑战性的语言。如果您想开始编写游戏,您可能会使用 PyGame 或 Löve 获得更大的成功。
  • Pixel-drawing in SDL2.0的可能重复

标签: c sdl


【解决方案1】:

试试:

SDL_LockSurface(screen);
put_pixel(screen,56,567,&pixel_white);
SDL_UnlockSurface(screen);

正如已经提到的,也许花点时间多学习一点 C 语言。特别是,考虑到您的问题,您可能会专注于函数参数和指针。

【讨论】:

    【解决方案2】:

    形参SDL_Surface *screen 只是一个指向 SDL_Surface 结构的指针,在您的情况下,您可能关心SDL_SetVideoMode() 返回的那个。

    pixel *p 是指向像素类型结构的指针,如下所示。

    typedef struct {
        Uint8 r;
        Uint8 g;
        Uint8 b;
        Uint8 alpha;
    } pixel;
    

    建议不要使用 screen->w,而是使用 pitch 计算基指针的偏移量,它是表面扫描线的长度,以字节为单位。

    而不是

        Uint32* p_screen = (Uint32*)screen->pixels;
        p_screen += y*screen->w+x;
        *p_screen = SDL_MapRGBA(screen->format,p->r,p->g,p->b,p->alpha);
    

    尝试使用:

        /* Get a pointer to the video surface's pixels in memory. */
        Uint32 *pixels = (Uint32*) screen->pixels;
    
        /* Calculate offset to the location we wish to write to */
        int offset = (screen->pitch / sizeof(Uint32)) * y + x;
    
        /* Compose RGBA values into correct format for video surface and copy to screen */
        *(pixels + offset) = SDL_MapRGBA(screen->format, p->r, p->g, p->b, p->alpha);     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2014-12-05
      • 1970-01-01
      • 2023-03-07
      • 2015-06-19
      相关资源
      最近更新 更多