2013-09-21 49 views
1

我有一個需要在SDL屏幕上繪製像素的項目。代碼位已被提供給我:使用SDL在屏幕上繪製像素C

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 *屏幕,int x,int y,pixel * p)行似乎很複雜。如果x和y是函數繪製參數,爲什麼然後在函數indata中聲明它們?我必須用put_pixel命令(something,x,y,something2)來調用put_pixel。如果我使用x = 56和y = 567,那麼在parentesis中聲明時是不是重置爲0?我應該在什麼東西和東西2,使其工作?

+0

我覺得這裏真正的問題是,你是一個初學者到C. C是一個具有挑戰性的語言學習在第一。如果您想開始編寫遊戲,您可能會在PyGame或Löve方面取得更多成功。 –

+0

[SDL2.0中的像素繪圖]的可能重複(http://stackoverflow.com/questions/20579658/pixel-drawing-in-sdl2-0) –

回答

2

嘗試:

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

而且因爲它已經提到,也許需要學習一點C語言的時間。特別是考慮到你的問題,你可能會關注函數參數和指針。

0

正式參數SDL_Surface *screen只是一個指向SDL_Surface結構的指針,在您的情況下,您可能會擔心由SDL_SetVideoMode()返回的結果。

pixel *p是一個指向像素類型結構的指針,如下所示。

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

代替使用絲網> W,它的建議來計算使用週期間距,即以字節爲單位的表面的掃描線的長度從基部指針字節偏移。

而是採用

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);