早些年用过GDI的同学都知道,用GDI绘图API函数画斜线那个锯齿有多恶心。就像下图第一行的三条斜线:
坦白说,45度斜线在抗锯齿以前还是蛮抗锯齿的,哈哈,抗不抗都没什么差别。
那第二行很自然就看得出是抗锯齿之后的效果。
话不多说,直接给大家上代码。
创建Win32应用程序,在cpp文件的顶部加入GDI+的引用:
#include <windows.h> #include <objidl.h> #define GDIPVER 0x0110 #include <gdiplus.h> #pragma comment(lib, "gdiplus.lib") using namespace Gdiplus; #define MAX_LOADSTRING 100
在cpp文件的主函数内添加初始化程序:
// 初始化全局字符串 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_SVV, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); // 执行应用程序初始化: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; }
在cpp文件的窗口过程回调函数中添加绘制斜线的程序:
case WM_PAINT: hdc = BeginPaint(hWnd, &ps); { // TODO: 在此添加任意绘图代码... Graphics graphics(hdc); Pen pen(Color(255, 255, 255, 255), 5); graphics.SetSmoothingMode(SmoothingMode::SmoothingModeHighSpeed); graphics.DrawLine(&pen, 100, 100, 400, 120); graphics.SetSmoothingMode(SmoothingMode::SmoothingModeAntiAlias8x8); graphics.DrawLine(&pen, 100, 300, 400, 320); graphics.SetSmoothingMode(SmoothingMode::SmoothingModeHighSpeed); graphics.DrawLine(&pen, 500, 100, 700, 300); graphics.SetSmoothingMode(SmoothingMode::SmoothingModeAntiAlias8x8); graphics.DrawLine(&pen, 500, 300, 700, 500); graphics.SetSmoothingMode(SmoothingMode::SmoothingModeHighSpeed); graphics.DrawLine(&pen, 800, 50, 820, 300); graphics.SetSmoothingMode(SmoothingMode::SmoothingModeAntiAlias8x8); graphics.DrawLine(&pen, 800, 250, 820, 500); } EndPaint(hWnd, &ps); break;
在cpp文件的主函数内添加反初始化程序:
// 主消息循环: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } GdiplusShutdown(gdiplusToken); return (int) msg.wParam;
打完,收工。
下载:抗锯齿演示程序 — SVV for Win7 32bit