1
votes

I have one large PNG file with all the textures I want to use in a 16x16 grid. Using SDL2 and the SDL2_Image libraries I can load it in as one big texture and have been trying to cut that texture into smaller textures. Is their any way of doing this?

I know I can crop the image when I RenderCopy it over. But I intend to modify the textures at points throughout the program so it would be easier to deal with multiple textures (I was thinking an array) rather then one big texture.

I'm happy to use Surfaces instead if that is what is needed to do this.

1
You could create an array of textures of size 16x16 and render the portions from the big texture to the small 16x16 textures using SDL_SetRenderTarget function - Aabesh Karmacharya
@Elvisjames I had a look on the wiki here but it has no examples of how to use it in a program. Could you give an example of how best to use this? - user2862660

1 Answers

0
votes
SDL_Surface* surf = IMG_Load("Image.PNG");
int width = surf->w;
int height = surf->h;
int clipPerRow = 16;
int clipPerColumn = 16;
SDL_Texture* texture = SDL_CreateTextureFromSurface(RENDERER,surf);
SDL_FreeSurface(surf);
SDL_Texture* clip[clipPerRow][clipPerColumn];
for(int i=0; i<clipPerRow; i++)
{
    for(int j=0;j<clipPerColumn;j++)
    {
        clip[i][j] = SDL_CreateTexture(RENDERER, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width/clipPerRow, height/clipPerColumn);
        SDL_SetTextureBlendMode(clip[i][j], SDL_BLENDMODE_BLEND);
        SDL_Rect rect = {i*width/clipPerRow,j*height/clipPerColumn, width/clipPerRow, height/clipPerColumn};
        SDL_SetRenderTarget(RENDERER, clip[i][j]);
        SDL_RenderCopy(RENDERER, texture, &rect, NULL);

    }
}
SDL_SetRenderTarget(RENDERER, NULL);
int x= 100;
int y =100;
while(!quit){
    while(SDL_PollEvent(&e)) if(e.type == SDL_QUIT) quit = 1;
    SDL_SetRenderDrawColor( RENDERER, 0x00, 0x00,0x00,0x00);
    SDL_RenderClear( RENDERER);
    for(int i=0; i<clipPerRow; i++)
    {
        for(int j=0;j<clipPerColumn;j++)
        {
            SDL_Rect rect = {x+i*width/clipPerRow,y+j*height/clipPerColumn, width/clipPerRow, height/clipPerColumn};
            SDL_RenderCopy(RENDERER,clip[i][j],NULL,&rect);
        }
    }
    SDL_RenderPresent(RENDERER);
}