D3D11绘制矩形代码
时间: 2023-07-02 11:17:07 浏览: 207
下面是使用Direct3D 11绘制一个矩形的代码示例:
```
// 定义矩形的顶点数据
struct Vertex
{
XMFLOAT3 position;
XMFLOAT4 color;
};
Vertex vertices[] =
{
{ XMFLOAT3(-1.0f, 1.0f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f) }, // 左上顶点,红色
{ XMFLOAT3( 1.0f, 1.0f, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f) }, // 右上顶点,绿色
{ XMFLOAT3( 1.0f, -1.0f, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f) }, // 右下顶点,蓝色
{ XMFLOAT3(-1.0f, -1.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f) } // 左下顶点,白色
};
// 定义矩形的索引数据
WORD indices[] =
{
0, 1, 2, // 第一个三角形
0, 2, 3 // 第二个三角形
};
// 创建顶点缓冲区
D3D11_BUFFER_DESC vertexBufferDesc = {};
vertexBufferDesc.ByteWidth = sizeof(Vertex) * 4;
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA vertexBufferData = {};
vertexBufferData.pSysMem = vertices;
vertexBufferData.SysMemPitch = 0;
vertexBufferData.SysMemSlicePitch = 0;
ID3D11Buffer* vertexBuffer = nullptr;
device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &vertexBuffer);
// 创建索引缓冲区
D3D11_BUFFER_DESC indexBufferDesc = {};
indexBufferDesc.ByteWidth = sizeof(WORD) * 6;
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA indexBufferData = {};
indexBufferData.pSysMem = indices;
indexBufferData.SysMemPitch = 0;
indexBufferData.SysMemSlicePitch = 0;
ID3D11Buffer* indexBuffer = nullptr;
device->CreateBuffer(&indexBufferDesc, &indexBufferData, &indexBuffer);
// 设置顶点缓冲区和索引缓冲区
UINT stride = sizeof(Vertex);
UINT offset = 0;
context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
context->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R16_UINT, 0);
// 设置输入布局和顶点着色器
context->IASetInputLayout(inputLayout);
context->VSSetShader(vertexShader, nullptr, 0);
// 设置渲染管线状态
context->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
context->RSSetState(rasterizerState);
context->RSSetViewports(1, &viewport);
context->OMSetDepthStencilState(depthStencilState, 0);
// 绘制矩形
context->DrawIndexed(6, 0, 0);
```
上述代码中,我们首先定义了一个 `Vertex` 结构体来表示顶点的位置和颜色信息。然后定义了一个包含 4 个顶点和 6 个索引的矩形。接着创建了顶点缓冲区和索引缓冲区,并将顶点数据和索引数据拷贝到缓冲区中。最后设置渲染管线的状态并调用 `DrawIndexed` 函数来绘制矩形。
阅读全文