2016-07-31 61 views
-2

我尝试使用SDL_RenderCopy() 但我只是得到一个黑匣子。 这是我的代码。如何获得SDL2中纹理的一部分?

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

编辑:

你想在这里做的是使纹理到屏幕的一部分。

有一种方法可以使用SDL_RenderCopy来做到这一点,但通过这样做,您只需从纹理中“取”出想要的部分,然后将其“拍”到屏幕上。

你想要的(按照我的理解)是取一部分纹理并保存到另一个纹理变量中,然后可以将其渲染到屏幕上。

第一个解决问题的办法是这样的:

// 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 *渲染器,SDL_Texture *纹理)

其中:

  • 渲染

渲染上下文

  • 质感

有针对性的质地,它必须与SDL_TEXTUREACCESS_TARGET标志被创建,或NULL默认渲染目标

让我们用同样的例子如前:

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

我不知道你想做什么,但我强烈推荐第一种方式。