我尝试使用SDL_RenderCopy()
来做到这一点
但我只是得到一个黑盒子。
这是我的代码。
static SDL_Texture* GetAreaTextrue(SDL_Rect rect, SDL_Renderer* renderer, SDL_Texture* source)
{
SDL_Texture* result = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h);
SDL_SetRenderTarget(renderer, result);
SDL_RenderCopy(renderer, source, &rect, NULL);
SDL_RenderPresent(renderer);
return result;
}
什么是正确的操作?
答案 0 :(得分:0)
编辑:
您要在此处执行的操作是将纹理的一部分渲染到屏幕上。
有一种方法可以通过使用SDL_RenderCopy来实现这一目标,但通过这样做,您只需"采取"你想要的纹理部分和#34; slap"它在你的屏幕上。
你想要的(根据我的理解)是获取纹理的一部分并将其保存到另一个纹理变量中,然后可以将其渲染到屏幕上。
问题的第一个解决方案如下:
// load your image in a SDL_Texture variable (myTexture for example)
// if the image is (256,128) and you want to render only the first half
// you need a rectangle of the same size as that part of the image
SDL_Rect imgPartRect;
imgPartRect.x = 0;
imgPartRect.y = 0;
imgPartRect.w = 32;
imgPartRect.h = 32;
// and the program loop should have a draw block looking like this:
SDL_SetRenderDrawColor( renderer, 0x00, 0x00, 0x00, 0xFF );
SDL_RenderClear( renderer );
SDL_RenderCopy( renderer, myTexture, &imgPartRect, NULL );
SDL_RenderPresent( renderer );
您尝试使用的方法具有渲染的中间纹理,然后将该纹理渲染到屏幕上。这里的问题是您将渲染器设置为在刚创建的纹理上绘制,但您从未重置渲染器以使用默认目标(屏幕)。
正如您在SDL文档here中看到的那样,第二个参数接收您希望您的renerer绘制的纹理,如果您想将其重置为默认目标(屏幕),则为NULL。
int SDL_SetRenderTarget(SDL_Renderer * renderer,SDL_Texture * texture)
其中:
- 渲染器
渲染上下文
- 质地
目标纹理,必须使用SDL_TEXTUREACCESS_TARGET标志创建,或者为默认渲染目标
让我们使用与以前相同的例子:
// first off let's build the function that you speak of
SDL_Texture* GetAreaTextrue(SDL_Rect rect, SDL_Renderer* renderer, SDL_Texture* source)
{
SDL_Texture* result = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h);
SDL_SetRenderTarget(renderer, result);
SDL_RenderCopy(renderer, source, &rect, NULL);
// the folowing line should reset the target to default(the screen)
SDL_SetRenderTarget(renderer, NULL);
// I also removed the RenderPresent funcion as it is not needed here
return result;
}
// load your image in a SDL_Texture variable (myTexture for example)
// if the image is (256,128) and you want to render only the first half
// you need a rectangle of the same size as that part of the image
SDL_Rect imgPartRect;
imgPartRect.x = 0;
imgPartRect.y = 0;
imgPartRect.w = 32;
imgPartRect.h = 32;
// now we use the function from above to build another texture
SDL_Texture* myTexturePart = GetAreaTextrue( imgPartRect, renderer, myTexture );
// and the program loop should have a draw block looking like this:
SDL_SetRenderDrawColor( renderer, 0x00, 0x00, 0x00, 0xFF );
SDL_RenderClear( renderer );
// here we render the whole newly created texture as it contains only a part of myTexture
SDL_RenderCopy( renderer, myTexturePart, NULL, NULL );
SDL_RenderPresent( renderer );
我不知道你想做什么,但我强烈推荐第一种方式。