参考1:https://www.bilibili.com/video/BV1cd4y1U7TC/?spm_id_from=333.999.0.0&vd_source=5b4cd3f84aab3b0261aa6b6791252d89参考2:https://blog.csdn.net/u013378269/article/details/103555482
CMakelist + Win32 API 图形学算法:03-DDA画线算法
#ifndef UNICODE
#define UNICODE
#endif
#include <math.h>
#include <Windows.h>
#include <stdio.h>
#include <wchar.h>
#include <WinBase.h>
#define PI 3.1415926 // PI
#define ROUND(d) int(d+0.5) // 四舍五入
// 点
class CP2
{
public:
CP2()
:_x(0)
,_y(0)
{
}
CP2(double x, double y)
:_x(x)
,_y(y)
{
}
virtual ~CP2() {};
public:
double _x;
double _y;
};
// DDA 算法
void DDALine(HDC hdc, CP2 p1, CP2 p2)
{
int dx = p2._x - p1._x;
int dy = p2._y - p1._y;
int steps; // 步数
int direction; // 方向 0--x方向 1--y方向
double xIncrement, yIncrement; // 每一步增加的数值 斜率
double x = p1._x, y = p1._y;
if (abs(dx)>abs(dy))
{
steps = abs(dx);
direction = 0; // 确认X步进主方向
}
else
{
steps = abs(dy);
direction = 1; // 确认y步进主方向,
}
xIncrement = double(dx) / double(steps); // x 每步骤增量
yIncrement = double(dy) / double(steps); // y 的每步增量
for (size_t k = 0; k <= steps; k++)
{
if (direction==0)
{
SetPixel(hdc, int(x), ROUND(y), 0x00FF0000);
}
else
{
SetPixel(hdc, ROUND(x), int(y), 0x00FF0000);
}
x += xIncrement; // x点+增量
y += yIncrement; // y点+增量
}
}
LRESULT CALLBACK WindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
RECT rc;
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rc);
SetMapMode(hdc, MM_ANISOTROPIC);
SetWindowExtEx(hdc, rc.right, rc.bottom, NULL);
SetViewportExtEx(hdc, rc.right, -rc.bottom, NULL);
SetViewportOrgEx(hdc, rc.right / 2, rc.bottom / 2, NULL);
int r = 200;
// 1. 绘制一条直线
DDALine(hdc, CP2(-300, 150), CP2(-300, -150));
// 2. 直线角间隔 5°
for (size_t i = 0; i < 360; i+=5)
{
double angle = i * PI / 180.0;
DDALine(hdc, CP2(0, 0), CP2(ROUND(cos(angle) * r), ROUND(sin(angle) * r)));
}
EndPaint(hwnd, &ps);
}
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
const wchar_t CLASS_NAME[] = L"03-DDA画线算法";
WNDCLASS wc = { };
wc.style = CS_HREDRAW | CS_VREDRAW; // 重新绘制整个工作区
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"03-DDA画线算法", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}