2012-05-04 34 views
0

對於我在C-SDL中的視頻遊戲,我需要使用我自己製作的spritesheet。 圖像尺寸是100×100和每一個畫面我想採取的是25×25如何在函數中加載圖片?

我在什麼地方找到一個不錯的功能,可以爲我做的:

// Wraps a rectangle around every sprite in a sprite sheet and stores it in an array of  rectangles(Clip[]) 

void spriteSheet(){ 

int SpriteWidth = 25; int SpriteHeight= 25; int SheetDimension = 4; 
int LeSprites = SheetDimension * SheetDimension;// Number of Sprites on sheet 
SDL_Rect Clip[LeSprites]; // Rectangles that will wrap around each sprite 

int SpriteXNum = 0;// The number sprite going from left to right 
int SpriteYNum = 0;// The number sprite going from top to bottom 
int YIncrement = 0;// Increment for each row. 
int i = 0; 
for(i = 0; i< LeSprites; i++){// While i is less than number of sprites 

    if(i = 0){// First sprite starts at 0,0 
     Clip[i].x = 0; 
     Clip[i].y = 0; 
     Clip[i].w = SpriteWidth; 
     Clip[i].h = SpriteHeight; 
    } 
    else{ 

     if(SpriteXNum < SheetDimension - 1){// If we have reached the end of the row, go back to the front of the next row 
      SpriteXNum = 0; 
     } 
     if(YIncrement < SheetDimension - 1){ 
      SpriteYNum += 1;       // Example of 4X4 Sheet 
     }           // ________________ 
     Clip[i].x = SpriteWidth * SpriteXNum;  // | 0 | 1 | 2 | 3 | 
     Clip[i].y = SpriteHeight * SpriteYNum;  // |===============| 
                // | 0 | 1 | 2 | 3 | 
                // |===============| 
     Clip[i].w = SpriteWidth;      // | 0 | 1 | 2 | 3 | 
     Clip[i].h = SpriteHeight;     // |===============| 
                // | 0 | 1 | 2 | 3 | 
    }            // |---------------| 
    SpriteXNum++; 
    YIncrement++; 
} 

} 

但現在我不知道我怎麼可以載入我的( PNG)圖片上應用此功能。

回答

1

看起來這段代碼只是給出了精靈表的每個單獨平方的剪切座標。它似乎並沒有與圖像互動。

如果你想加載PNG你應該使用額外的SDL_image library。它將生成一個SDL_Surface指針,當您撥打SDL_BlitSurface將其繪製到屏幕上時,可以使用該指針與剪切座標。

請注意,您應該嘗試從圖像本身獲取SpriteDimension等值(將圖像寬度(w)和高度(h)除以各個精靈的大小)。

未來,您可以通過設計一個SpriteSheet類來擴展這個想法,該類包含其計算出的裁剪位置和其他關於精靈表的信息,以及根據需要將調用打包爲SDL_BlitSurface

+0

謝謝你的回答,但我需要數組中的每個圖片的正方形。所以我可以像image [0]圖像[12]那樣調用圖像。 –

+0

這種類型會破壞精靈表的目的,但在這種情況下,您可以爲每個精靈創建一個新的表面(使用SDL_CreateSurface)然後使用SDL_BlitSurface以與繪製到屏幕表面相似的方式將其粘貼到該表面中。之後,只需將表面指針存儲在一個數組中。 – ravuya