VC++ 用MOVETtoEX和Lineto绘制连贯流畅线条

之前学VC++尝试了使用setpixel函数画线,结果画出来的线断断续续,一点都不连贯,那么怎么使其画出连贯流畅的线条呢?

效果图:


对比setpixel()


先来看代码:

#include<Windows.h>
#include<tchar.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
BOOLEAN InitWindowsClass(HINSTANCE, int);


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
if (!InitWindowsClass(hInstance, nCmdShow))
{
MessageBox(NULL, _T("创建窗口失败!"), _T("创建窗口"), NULL);
return 1;
}
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}




LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
static bool  isDrawPoint = 0;
static int x = 0, y = 0;
static int x1 = 0, y1 = 0;
x = LOWORD(lParam);
y = HIWORD(lParam);
switch (message)
{
case WM_LBUTTONDOWN:
isDrawPoint = true;
x1 = x;
y1 = y;


InvalidateRect(hWnd, NULL, false);
break;
case WM_LBUTTONUP:

isDrawPoint = false;
InvalidateRect(hWnd, NULL, false);
break;
case WM_RBUTTONDOWN:
InvalidateRect(hWnd, NULL, true);
break;
case WM_MOUSEMOVE:
if (isDrawPoint)
{
hdc = GetDC(hWnd);
x = LOWORD(lParam);
y = HIWORD(lParam);
MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, x, y);
x1 = x;
y1 = y;
ReleaseDC(hWnd,hdc);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);




EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
BOOLEAN InitWindowsClass(HINSTANCE hInstance, int nCmdShow)
{
WNDCLASSEX wndclass;
HWND hWnd;


wndclass.cbSize = sizeof(WNDCLASSEX);
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.hCursor = LoadCursor(hInstance, IDC_ARROW);
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hInstance = hInstance;
wndclass.lpfnWndProc = WndProc;
wndclass.lpszClassName = _T("窗口1");
wndclass.lpszMenuName = NULL;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wndclass))
return FALSE;


hWnd = CreateWindow(_T("窗口1"), _T("鼠标画线示例"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
if (!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;

}


核心代码:

 case WM_MOUSEMOVE:
if (isDrawPoint)
{
hdc = GetDC(hWnd);
x = LOWORD(lParam);
y = HIWORD(lParam);
MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, x, y);
x1 = x;
y1 = y;
ReleaseDC(hWnd,hdc);
}
break;

我也是初学VC++,第一次知道可以不用再paint中画图,直接在move中画图即可。

这里使用类似动态跟踪的功能,先定下鼠标左键按下的初始点,在move到鼠标指针现在的位置,接着将lineto的鼠标坐标赋值给初始点,就这样循环往复即可实现不断的连线。


之所以setpixel函数会出现断断续续,我认为可能是由于每一次的刷新速率跟不上鼠标位置变化率,当鼠标飞快在用户区滑动时,setpixel未能及时捕获到每一个时刻的坐标位点。


但同样可以定义一个point数组,例如point[100]={0,0}存放setpixel的值,再加一个判断条件,当抬起鼠标时,将数组里的元素统统连接,这样也可以实现画流畅线条。


如有疑问欢迎交流

猜你喜欢

转载自blog.csdn.net/qq_41953239/article/details/80102520