Search code examples
c++directxtoolkitspritebatch

DirectX Toolkit C++ SpriteBatch Draw Rectangle


I am using DirectX 11, DirectX Toolkit and C++. How can I create a rectangle with a blue border for spritebatch ? I'm guessing I need to create a texture in memory perhaps with a 1 pixel blue border ?

ComPtr<ID3D11ShaderResourceView>    spriteSheet_;

ComPtr<ID3D11Resource> resource;
    CreateDDSTextureFromFile(d3dDevice_, L"mytex.dds", resource.GetAddressOf(),
        spriteSheet_.ReleaseAndGetAddressOf());

batch->Draw(spriteSheet_.Get(), position, &sourceRect, DirectX::Colors::White,
        rotation_, spriteOrigin_, scale_, DirectX::SpriteEffects_None, depth_);

Solution

  • You can use SpriteBatch to draw a single-pixel texture as you described--you could use a white texture and use the SpriteBatch tinting to make it Blue.

    Here is some simple code for programmatically creating a 1x1 white texture in Direct3D 11:

        Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> pWhiteTexture;
    
        static const uint32_t s_pixel = 0xffffffff;
    
        D3D11_SUBRESOURCE_DATA initData = { &s_pixel, sizeof(uint32_t), 0 };
    
        D3D11_TEXTURE2D_DESC desc;
        memset( &desc, 0, sizeof(desc) );
        desc.Width = desc.Height = desc.MipLevels = desc.ArraySize = 1;
        desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        desc.SampleDesc.Count = 1;
        desc.Usage = D3D11_USAGE_IMMUTABLE;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    
        Microsoft::WRL::ComPtr<ID3D11Texture2D> tex;
        HRESULT hr = mDevice->CreateTexture2D( &desc, &initData, &tex );
    
        DX::ThrowIfFailed(hr);
    
        D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
        memset( &SRVDesc, 0, sizeof( SRVDesc ) );
        SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
        SRVDesc.Texture2D.MipLevels = 1;
    
        hr = mDevice->CreateShaderResourceView( tex.Get(), &SRVDesc, &pWhiteTexture );
    
        DX::ThrowIfFailed(hr);
    

    A more efficient solution would be to use PrimitiveBatch to draw a blue quad where you want it located.

    See the DirectX Tool Kit tutorial Simple rendering