我正在使用 DirectX 11 SDK 并为纹理渲染一些东西(它的工作原理)。比使用 D3DX11SaveTextureToFile 将输出保存到 PNG 纹理。一切正常,但我没有得到透明度。
我想让背景(没有渲染任何元素的空间)透明。而不是这个,我得到了一些背景。
我试图将float ClearColor[4]
forClearRenderTargetView
函数更改为,{ 0.0f, 0.0f, 0.0f, 1.0f }
因为我认为最后一个是 alpha 和1.0f给我透明度,但这对我不起作用(对于 0.0f 也是如此)。
这是我的代码中可能有用的部分:
混合状态(我认为这很好,它们适用于在屏幕上渲染透明元素 - 当然监视器的屏幕总是有一些“背景”,PNG文件没有):
D3D11_BLEND_DESC blendDesc;
ZeroMemory(&blendDesc, sizeof(D3D11_BLEND_DESC) );
blendDesc.AlphaToCoverageEnable = false;
blendDesc.IndependentBlendEnable = false;
blendDesc.RenderTarget[0].BlendEnable = true;
blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL ;
ID3D11BlendState * blendState;
if(FAILED(device->CreateBlendState(&blendDesc, &blendState))){
//...
}
g_pImmediateContext->OMSetBlendState(blendState,NULL,0xffffffff);
和:
// Setup the render target texture description.
textureDesc.Width = textureWidth;
textureDesc.Height = textureHeight;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
textureDesc.SampleDesc.Count = 1;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
...
//Create the render target texture.
result = device->CreateTexture2D(&textureDesc, NULL, &renderTargetTexture);
...
result = device->CreateShaderResourceView(renderTargetTexture,
&shaderResourceViewDesc, &shaderResourceView);
...
g_pImmediateContext->OMSetRenderTargets(1, &renderTargetView,
g_pDepthStencilView);
float ClearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; //red, green, blue, alpha
g_pImmediateContext->ClearRenderTargetView( renderTargetView, ClearColor );
//clear the depth buffer to 1.0 (max depth)
g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView,
D3D11_CLEAR_DEPTH, 1.0f, 0 );
...
//render here
...
D3DX11SaveTextureToFile(g_pImmediateContext, renderTargetTexture,
D3DX11_IFF_BMP, CommonFunctions::s2ws(newTextureName).c_str());