原文轉自 https://wenku.baidu.com/view/b5460979700abb68a982fbcf.html
在常規條件下,MFC畫出來的圖形、文字都是有鋸齒的。如下圖所示:
怎樣才能畫出不帶鋸齒的圖形呢?要用到GDI+這個MFC庫。下面將以案例的方式講述如何通過MFC畫出不帶鋸齒的圖形。
一、建立一個簡單的MFC應用
一個簡單的MFC應用包含兩個文件,Hello.h和Hello.cpp。建立的方法是在VS中建立一個空項目,然而添加頭文件Hello.h和源文件Hello.cpp
//Hello.h #include <afxwin.h> class CMyApp : public CWinApp { public: virtual BOOL InitInstance(); }; class CMainWindow : public CFrameWnd { public: CMainWindow(); protected: afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() };
// Hello.cpp #include <afxwin.h> #include "Hello.h" CMyApp myApp; BOOL CMyApp::InitInstance() { m_pMainWnd = new CMainWindow; m_pMainWnd->ShowWindow(m_nCmdShow); m_pMainWnd->UpdateWindow(); return TRUE; } BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd) ON_WM_PAINT() END_MESSAGE_MAP() CMainWindow::CMainWindow() { Create(NULL, _T("The Hello Application")); } void CMainWindow::OnPaint() { CPaintDC dc(this); dc.MoveTo(10, 10); dc.LineTo(200, 400); dc.MoveTo(10, 15); dc.LineTo(200, 500); }
下面開始編譯程序。這里要注意的是,應該修改項目屬性中【鏈接器】的設置,在【高級】選項卡中的【入口】選項中,填入WinMainCRTStartup。此外,要遭項目屬性的【配置屬性】選項卡中,修改【MFC的使用】項目,修改為【在共享DLL中使用MFC】。
這樣就可以編輯並運行程序了。程序運行的效果如上圖所示,所畫的兩條曲線是帶有鋸齒的。 要想得到反鋸齒的、渲染細膩的線條,就要對上述程序做一些修改。
首先要修改頭文件Hello.h,將GDI+的頭文件引入,並在CMyApp中定義新的成員變量m_gdiplusToken,覆蓋CMyApp繼承而來的ExitInstance( )函數。具體如下
//Hello.h #include <afxwin.h> #include <Gdiplus.h> //引入頭函數 #pragma comment(lib, "Gdiplus.lib") // 引入鏈接庫 class CMyApp : public CWinApp { public: virtual BOOL InitInstance(); virtual int ExitInstance(); private: ULONG_PTR m_gdiplusToken; }; class CMainWindow : public CFrameWnd { public: CMainWindow(); protected: afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() };
下面需要在Hello.cpp中做出相應的調整。主要調整的是 CMyApp::InitInstance( ), CMyApp::ExitInstance( ) 和 CMainWindow::OnPaint( )
// Hello.cpp #include <afxwin.h> #include "Hello.h" CMyApp myApp; BOOL CMyApp::InitInstance() { m_gdiplusToken = 0; Gdiplus::GdiplusStartupInput gpSI; Gdiplus::GdiplusStartup(&m_gdiplusToken, &gpSI, NULL); m_pMainWnd = new CMainWindow; m_pMainWnd->ShowWindow(m_nCmdShow); m_pMainWnd->UpdateWindow(); return TRUE; } int CMyApp::ExitInstance() { Gdiplus::GdiplusShutdown(m_gdiplusToken); return __super::ExitInstance(); } BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd) ON_WM_PAINT() END_MESSAGE_MAP() CMainWindow::CMainWindow() { Create(NULL, _T("The Hello Application")); } void CMainWindow::OnPaint() { CPaintDC dc(this); Gdiplus::Graphics graphics(dc.m_hDC); Gdiplus::Pen red(Gdiplus::Color(255, 255, 0, 0), 1); Gdiplus::Pen blue(Gdiplus::Color(255, 0, 0, 255), 1); graphics.SetSmoothingMode(Gdiplus::SmoothingModeHighQuality); graphics.DrawLine(&red, 10, 10, 200, 400); graphics.DrawLine(&blue, 10, 15, 200, 500); }
這樣修改后的程序就能夠畫出反鋸齒的曲線了。如下圖所示