SDL2 尝试裁剪纹理或表面

SDL2 Trying to crop a texture or surface

本文关键字:表面 纹理 裁剪 SDL2      更新时间:2023-10-16

我有一个大的PNG文件,其中包含我想在16x16网格中使用的所有纹理。使用 SDL2 和SDL2_Image库,我可以将其加载为一个大纹理,并一直尝试将该纹理剪切成较小的纹理。他们有什么办法做到这一点吗?

我知道我可以在渲染复制图像时裁剪图像。但是我打算在整个程序中修改纹理,以便更容易处理多个纹理(我正在考虑一个数组)而不是一个大纹理。

我很乐意使用表面来代替,如果这是这样做所需要的。

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