1. 程式人生 > >VS2015 中使用GDI+(超實用,親測可用)

VS2015 中使用GDI+(超實用,親測可用)

  1. 新建對話方塊程式,在stdafx.h中新增:
#include <GdiPlus.h>
#pragma comment(lib, "GdiPlus.lib")
using namespace Gdiplus;
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

 在應用程式類新增一個保護許可權的資料成員:

[cpp] view plain copy
  1. ULONG_PTR m_gdiplusToken;  

然後在對話方塊類的OnInitDialog加上下面初始化程式碼:

[cpp] view plain copy
  1. BOOL CGDIDlg::OnInitDialog()
  2. {  
  3.     Gdiplus::GdiplusStartupInput StartupInput;  
  4.     GdiplusStartup(&m_gdiplusToken,&StartupInput,NULL);  
  5. }  

上面程式碼的作用是初始化GDI+資源。


  在應用程式類的OnFinalRelease加上下面程式碼:

void CGDIDlg::OnFinalRelease()
{
// TODO: 在此新增專用程式碼和/或呼叫基類
Gdiplus::GdiplusShutdown(m_gdiplusToken);
CDialogEx::OnFinalRelease();
}

上面程式碼的作用是銷燬GDI+資源。


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 新增具體GDI繪圖程式碼。(新增一個影象控制元件,ID為IDC_PIC ) 
    如在對話方塊CxxDlg的Onpaint中最後新增:
void CGDIDlg::OnPaint()
{
	if (IsIconic())
	{
		.../*省略*/
	}
	else
	{
		CPaintDC dc(this); // 用於繪製的裝置上下文
		Graphics graphics(dc.GetSafeHdc());
		int offsetX = 100;
		int offsetY = 50;
		Point points[5] = {
			Point(offsetX+50,offsetY),
			Point(offsetX + 100,offsetY + 50),
			Point(offsetX + 50,offsetY+100),
			Point(offsetX ,offsetY + 50),
			Point(offsetX+50,offsetY)
		};
		Pen pen1(Color(0, 0, 255), 2);
		Pen pen2(Color(255, 0, 0), 2);
		graphics.DrawCurve(&pen1, points, 5);
		graphics.DrawLine(&pen1, 0, 0, 200, 100);
		/*設定平滑繪圖*/
		graphics.SetSmoothingMode(SmoothingModeHighQuality);
		/*建立矩陣*/
		Matrix matrix(1.0f,0.0f,0.0f,1.0f,0.0f,0.0f);
		matrix.Translate(50.f,150.0f,MatrixOrderAppend);
		graphics.SetTransform(&matrix);
		graphics.DrawCurve(&pen2, points, 5);
		graphics.DrawLine(&pen2, 0, 0, 200, 100);
		CDialogEx::OnPaint();
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 編譯執行即可。