在GDI里面,你要想開(kāi)始自己的繪圖工作,必須先獲取一個(gè)device context handle,然后把這個(gè)handle作為繪圖復(fù)方法的一個(gè)參數(shù),才能完成任務(wù)。同時(shí),device context handle是同一定的繪圖屬性綁定在一起的,諸如畫(huà)筆、話刷等等,你必須在畫(huà)線之前創(chuàng)建自己的畫(huà)筆,然后使用selectObject方法把這個(gè)畫(huà)筆同已經(jīng)獲取的device context handle綁定,才能使用LineTo等方法開(kāi)始畫(huà)線。不然,你畫(huà)出來(lái)的線使用的是默認(rèn)的屬性:寬度(1),顏色(黑色)。
但是,在GDI+里面,畫(huà)線方法DrawLine把畫(huà)筆Pen直接作為一個(gè)參數(shù),這樣,一定的畫(huà)筆就不需要同device context handle 直接綁定了。
下面是GDI和GDI+兩者畫(huà)線代碼的演示:
GDI:
HDC hdc;
PAINTSTRUCT ps;
HPEN hPen;
HPEN hPenOld;
hdc = BeginPaint(hWnd, &ps);
hPen = CreatePen(PS_SOLID, 3, RGB(255, 0, 0));
hPenOld = (HPEN)SelectObject(hdc, hPen);
MoveToEx(hdc, 20, 10, NULL);
LineTo(hdc, 200, 100);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
EndPaint(hWnd, &ps);
GDI+:
HDC hdc;
PAINTSTRUCT ps;
Pen* myPen;
Graphics* myGraphics;
hdc = BeginPaint(hWnd, &ps);
myPen = new Pen(Color(255, 255, 0, 0), 3);
myGraphics = new Graphics(hdc);
myGraphics->DrawLine(myPen, 20, 10, 200, 100);
delete myGraphics;
delete myPen;
EndPaint(hWnd, &ps);