我希望通过DirectX 11将我的前端或后端缓冲区的内容捕获到字节数组中,然后我可以将其用作纹理或用作创建文件的源。我已经设置了交换链并进行了大量渲染,目前有以下代码 - 我确保在调用Present之后调用它。请注意,html标签已被保留。
ID3D11Texture2D* pSurface;
HRESULT hr = m_swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), reinterpret_cast< void** >( &pSurface ) );
if( pSurface )
{
const int width = static_cast<int>(m_window->Bounds.Width * m_dpi / 96.0f);
const int height = static_cast<int>(m_window->Bounds.Height * m_dpi / 96.0f);
unsigned int size = width * height;
if( m_captureData )
{
freeFramebufferData( m_captureData );
}
m_captureData = new unsigned char[ width * height * 4 ];
ID3D11Texture2D* pNewTexture = NULL;
D3D11_TEXTURE2D_DESC description =
{
width, height, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM,
{ 1, 0 }, // DXGI_SAMPLE_DESC
D3D11_USAGE_STAGING,
0, D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE, 0
};
HRESULT hr = m_d3dDevice->CreateTexture2D( &description, NULL, &pNewTexture );
if( pNewTexture )
{
m_d3dContext->CopyResource( pNewTexture, pSurface );
D3D11_MAPPED_SUBRESOURCE resource;
unsigned int subresource = D3D11CalcSubresource( 0, 0, 0 );
HRESULT hr = m_d3dContext->Map( pNewTexture, subresource, D3D11_MAP_READ, 0, &resource );
//resource.pData; // TEXTURE DATA IS HERE
const int pitch = width << 2;
const unsigned char* source = static_cast< const unsigned char* >( resource.pData );
unsigned char* dest = m_captureData;
for( int i = 0; i < height; ++i )
{
memcpy( dest, source, width * 4 );
source += pitch;
dest += pitch;
}
m_captureSize = size;
m_captureWidth = width;
m_captureHeight = height;
return;
}
freeFramebufferData( m_captureData );
}
当alpha值为零时,它总是给我黑色。
通常我可以使用GDI互操作选项来使用BitBlt将位图从交换链中复制出来 - 但由于我的限制,这不是一个有效的解决方案。
同时,包含执行此操作的功能的D3DX库也不可行。