从来源 SDL_Texture 中提取 SDL_Texture

Extract an SDL_Texture from a source SDL_Texture

我有以下功能,可以从与它们平铺的更大纹理中提取 64x64 像素纹理:

SDL_Texture* cropTexture (SDL_Texture* src, int x, int y)
{
    SDL_Texture* dst = SDL_CreateTexture(gRenderer, gSurface->format->format, SDL_TEXTUREACCESS_TARGET, 64, 64);
    SDL_Rect rect = {64 * x, 64 * y, 64, 64};
    SDL_SetRenderTarget(gRenderer, dst);
    SDL_RenderCopy(gRenderer, src, &rect, NULL);

    return dst;
}

现在,当我这样调用函数时:

SDL_Texture* txt_walls [3];
txt_walls[0] = cropTexture (allWalls, 0, 0);
txt_walls[1] = cropTexture (allWalls, 0, 1);
txt_walls[2] = cropTexture (allWalls, 4, 3);

然后 txt_walls[2] 产生黑色纹理(或至少未初始化)。

当我添加一行无意义的代码时:

SDL_Texture* txt_walls [3];
txt_walls[0] = cropTexture (allWalls, 0, 0);
txt_walls[1] = cropTexture (allWalls, 0, 1);
txt_walls[2] = cropTexture (allWalls, 4, 3);
cropTexture (allWalls, 1, 1); // whatever, ignore the returned object

那么txt_walls[2]是正确的:这个数组位置的纹理在我的程序中渲染得很好。

cropTexture 有什么问题吗?我是 C++ 和 SDL2 的新手。

裁剪纹理后需要将渲染目标设置回默认值,否则会继续在纹理上绘制。在 cropTexture 中的 return 之前添加:

SDL_SetRenderTarget(gRenderer, NULL);