DirectWrite 简单示例

一个简单示例

#include <windows.h>
#include <intsafe.h>
#include <d2d1.h>
#include <d2d1helper.h>
#include <dwrite.h>
#include <string.h>

#pragma comment(lib,"d2d1.lib")
#pragma comment(lib, "dwrite.lib")
#pragma comment(lib, "windowscodecs.lib")

// Direct2D
ID2D1Factory* pD2DFactory;
ID2D1HwndRenderTarget* pRT;
ID2D1SolidColorBrush* pBlackBrush;

// DirectWrite
IDWriteFactory* pDWriteFactory;
IDWriteTextFormat* pTextFormat;

//初始化
void init()
{
	// Create Direct2D factory.
	HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pD2DFactory);

	// Create a shared DirectWrite factory.
	if (SUCCEEDED(hr))
	{
		hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory),
			reinterpret_cast<IUnknown**>(&pDWriteFactory));
	}

	// Create a text format
	if (SUCCEEDED(hr))
	{
		hr = pDWriteFactory->CreateTextFormat(
			L"Courier New",             // Font family name.
			NULL,                       // Font collection (NULL sets it to use the system font collection).
			DWRITE_FONT_WEIGHT_REGULAR,
			DWRITE_FONT_STYLE_NORMAL,
			DWRITE_FONT_STRETCH_NORMAL,
			36.0f,
			L"en-us",
			&pTextFormat
		);
	}

	if (SUCCEEDED(hr))
	{
		RECT rc;
		GetClientRect(hWnd, &rc);

		// Create a Direct2D render target.
		hr = pD2DFactory->CreateHwndRenderTarget(D2D1::RenderTargetProperties(),
			D2D1::HwndRenderTargetProperties(hWnd, D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top)),
			&pRT);

		// Create a black brush.
		if (SUCCEEDED(hr)) {
			hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBlackBrush);
		}
	}
}

void DrawD2DContent()
{
	RECT rc;
	GetClientRect(hWnd, &rc);

	pRT->BeginDraw();
	pRT->SetTransform(D2D1::IdentityMatrix());
	pRT->Clear(D2D1::ColorF(D2D1::ColorF::White));

	// Use the DrawText method of the D2D render target interface to draw.
	// The string to display.
	pRT->DrawText(
		L"Hello World using DirectWrite!",        // The string to render.
		(UINT32)wcslen(L"Hello World using DirectWrite!"),    // The string's length.
		pTextFormat,    // The text format.
		D2D1::Rect(
			rc.top,
			rc.left,
			rc.right - rc.left,
			rc.bottom - rc.top
		),       // The region of the window where the text will be rendered.
		pBlackBrush     // The brush used to draw the text.
	);

	pRT->EndDraw();
}

void OnResize(UINT width, UINT height)
{
	if (pRT)
	{
		D2D1_SIZE_U size;
		size.width = width;
		size.height = height;
		pRT->Resize(size);
	}
}

template <class T> inline void SafeRelease(T **ppT)
{
	if (*ppT)
	{
		(*ppT)->Release();
		*ppT = NULL;
	}
}

void destruct()
{
	SafeRelease(&pD2DFactory);
	SafeRelease(&pRT);
	SafeRelease(&pBlackBrush);
	SafeRelease(&pDWriteFactory);
	SafeRelease(&pTextFormat);
}

参考 MSDN

本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院