本例主要是对比D2D和GDI在绘制文字、线条的区别,以及D2D与GDI+在绘制图片时的区别。
D2D是基于COM组件开发的,使用前的CoInitialize(NULL)是必须的;另外,GDI+的初始化GdiplusStartup()也别忘了。
废话少说,完整代码如下:
// D2DDemo.cpp : 定义应用程序的入口点。
//
#include "stdafx.h"
#include "D2DDemo.h"
#include <D2D1.h>
#include <DWrite.h>
#pragma comment(lib, "D2D1")
#pragma comment(lib, "DWrite")
#include <atlbase.h>
#include <atlcom.h>
#include <wincodec.h>
#pragma comment(lib, "windowscodecs")
#include <GdiPlus.h>
#pragma comment(lib, "GdiPlus")
using namespace Gdiplus;
#define MAX_LOADSTRING 100
// 全局变量:
HINSTANCE hInst; // 当前实例
TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名
// 此代码模块中包含的函数的前向声明:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
BOOL InitD2DResource();
BOOL InitDeviceResource(HWND hWnd);
void D2DDraw();
BOOL OnCreate(HWND hWnd);
HRESULT LoadBitmapFromFile(
ID2D1RenderTarget *pRenderTarget,
IWICImagingFactory *pIWICFactory,
PCWSTR uri,
UINT destinationWidth,
UINT destinationHeight,
ID2D1Bitmap **ppBitmap
);
//这里来定义全局变量
CComPtr<ID2D1Factory> g_pD2d1Factory;
CComPtr<IDWriteFactory> g_pDWriteFactory;
CComPtr<IDWriteTextFormat> g_pDWriteFormat;
CComPtr<ID2D1HwndRenderTarget> g_pD2D1HwndRender;
CComPtr<ID2D1GdiInteropRenderTarget> g_pD2DGdiRender;
CComPtr<IWICImagingFactory> g_pWicImageFactory;
CComPtr<ID2D1Bitmap> g_pBkImage;
LOGFONT g_logFont;
HFONT g_hTextFont = NULL;
#define FREE_COM_PTR(x) { if (x) { x->Release(); x = NULL; } }
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
HRESULT hr = CoInitialize(NULL);
ULONG_PTR ptr;
GdiplusStartupInput input;
GdiplusStartup(&ptr, &input, NULL);
// TODO: 在此放置代码。
MSG msg;
HACCEL hAccelTable;
memset(&g_logFont, 0, sizeof(LOGFONT));
g_logFont.lfHeight = 40;
g_logFont.lfWidth = 0;
g_logFont.lfWeight = FW_NORMAL;
g_logFont.lfCharSet = DEFAULT_CHARSET;
g_logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
g_logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
g_logFont.lfQuality = DEFAULT_QUALITY;
g_logFont.lfPitchAndFamily = DEFAULT_PITCH|FF_SWISS;
wcscpy(g_logFont.lfFaceName, L"微软雅黑");