#include <d2d1.h>
#include <d2d1helper.h>
// 初始化 Direct2D 和相关资源
HRESULT InitializeD2D(HWND hwnd, ID2D1Factory** ppFactory, ID2D1HwndRenderTarget** ppRenderTarget)
{
// 创建 Direct2D 工厂
HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, ppFactory);
if (SUCCEEDED(hr)) {
RECT rc;
GetClientRect(hwnd, &rc);
// 创建 Direct2D 渲染目标
hr = (*ppFactory)->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(hwnd, D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top)),
ppRenderTarget
);
}
return hr;
}
// 绘制椭圆形
void DrawEllipse(ID2D1HwndRenderTarget* pRenderTarget)
{
// 开始绘制
pRenderTarget->BeginDraw();
// 清空背景色
pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
// 创建椭圆形
D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(200.0f, 200.0f), 100.0f, 50.0f);
// 设置椭圆形的笔刷颜色
pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Blue), NULL, &pBrush);
// 绘制椭圆形
pRenderTarget->DrawEllipse(ellipse, pBrush);
// 结束绘制
pRenderTarget->EndDraw();
}
// 释放资源
void Cleanup(ID2D1Factory* pFactory, ID2D1HwndRenderTarget* pRenderTarget)
{
if (pRenderTarget != NULL) {
pRenderTarget->Release();
}
if (pFactory != NULL) {
pFactory->Release();
}
}
// 主窗口过程
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static ID2D1Factory* pFactory = NULL;
static ID2D1HwndRenderTarget* pRenderTarget = NULL;
switch (message) {
case WM_CREATE:
if (FAILED(InitializeD2D(hwnd, &pFactory, &pRenderTarget))) {
return -1; // 创建失败,结束窗口
}
return 0;
case WM_PAINT:
DrawEllipse(pRenderTarget);
ValidateRect(hwnd, NULL);
return 0;
case WM_DESTROY:
Cleanup(pFactory, pRenderTarget);
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
int main()
{
// 窗口创建和消息循环代码...
return 0;
}
在这个示例中,DrawEllipse 函数使用 DrawEllipse 方法绘制了一个蓝色的椭圆形。你可以根据需要修改颜色、位置和大小等参数。要运行这个示例,确保你的项目链接了 Direct2D 库,并且相关的头文件和库文件路径设置正确。
转载请注明出处:http://www.zyzy.cn/article/detail/25445/Win32 API/D2d1helper.h/椭圆形