概述
请注意在项目->属性中设置包含目录和库目录
#include <Windows.h>
#include <d2d1.h>
#pragma comment(lib,"d2d1.lib")
#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } }
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
ID2D1Factory* g_pd2dFac = NULL;
ID2D1HwndRenderTarget* g_pRenderTarget = NULL;
ID2D1SolidColorBrush* g_pBlackBrush = NULL;
HRESULT D2D_Init(HWND);
void D2D_Paint(HWND);
void D2D_CleanUp();
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
static TCHAR szAppName[] = TEXT("D2DDrawTest");
HWND hwnd;
MSG msg = { 0 };
WNDCLASSEX wndclass = { 0 };
wndclass.cbSize = sizeof(WNDCLASSEX);
wndclass.lpfnWndProc = WndProc;
wndclass.hInstance = hInstance;
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.style = CS_VREDRAW | CS_HREDRAW;
if (!RegisterClassEx(&wndclass)) {
return -1;
}
hwnd = CreateWindow(szAppName, TEXT("D2DDrawTest"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH, WINDOW_HEIGHT, NULL, NULL, hInstance, NULL);
if (FAILED(D2D_Init(hwnd))) {
return -1;
}
MoveWindow(hwnd, 250, 80, WINDOW_WIDTH, WINDOW_HEIGHT, TRUE);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (msg.message != WM_QUIT) {
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
UnregisterClass(szAppName, wndclass.hInstance);
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_PAINT:
D2D_Paint(hwnd);
ValidateRect(hwnd, NULL);
break;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
DestroyWindow(hwnd);
break;
case WM_DESTROY:
D2D_CleanUp();
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
void D2D_Paint(HWND hwnd) {
g_pRenderTarget->BeginDraw();
g_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
g_pRenderTarget->DrawRectangle(D2D1::Rect(100.f, 100.f, 700.f, 500.f), g_pBlackBrush);
g_pRenderTarget->EndDraw();
}
HRESULT D2D_Init(HWND hwnd) {
if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &g_pd2dFac))) {
return E_FAIL;
}
RECT rc;
GetClientRect(hwnd, &rc);
if (FAILED(g_pd2dFac->CreateHwndRenderTarget(D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(hwnd, D2D1::SizeU(WINDOW_WIDTH, WINDOW_HEIGHT)), &g_pRenderTarget))) {
return E_FAIL;
}
if (FAILED(g_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &g_pBlackBrush))) {
return E_FAIL;
}
return S_OK;
}
void D2D_CleanUp() {
SAFE_RELEASE(g_pBlackBrush)
SAFE_RELEASE(g_pRenderTarget)
SAFE_RELEASE(g_pd2dFac)
}
最后
以上就是大方大象为你收集整理的用Direct2D绘制一个矩形的全部内容,希望文章能够帮你解决用Direct2D绘制一个矩形所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复