Windows 控制台下的绘图方法
程序代码:
#include <Windows.h> #include <ctime> #include <cmath> #include <conio.h> // 全局常数及变量 const double PI(2 * asin(1.0)); // 圆周率 const WCHAR K_ENTER(0x000D); // Enter键码 const RECT Border = { 10, 10, 620, 350 }; // 图框位置及尺寸 const POINT Origin = { 20, 170 }; // 坐标原点位置 const double Scale(80.0); // 缩放比例 const double Increase(0.0001); // 自变量微元增量dx HDC hDC(GetDC(GetConsoleWindow())); // 绘图设备 // 函数原型 void DrawBorder(void); // 绘制图框 void DrawAxes(void); // 绘制坐标轴 void DrawGraph(void); // 绘制图像 void Wait(void); // 等待按键 // 程序入口 void wmain(void) { DrawBorder(); DrawAxes(); DrawGraph(); Wait(); ReleaseDC(NULL, hDC); } void DrawBorder(void) { HPEN hPen(CreatePen(PS_SOLID, 1, RGB(0,255,0))); HBRUSH hBrush(CreateSolidBrush(RGB(0,0,0))); SelectObject(hDC, hPen); SelectObject(hDC, hBrush); Rectangle(hDC, Border.left, Border.top, Border.right, Border.bottom); DeleteObject(hPen); DeleteObject(hBrush); } void DrawAxes(void) { HPEN hPen(CreatePen(PS_SOLID, 1, RGB(0, 255, 255))); SelectObject(hDC, hPen); MoveToEx(hDC, Origin.x, Origin.y, NULL); LineTo(hDC, Border.right - 10, Origin.y); DeleteObject(hPen); } void DrawGraph(void) { HPEN hPen(CreatePen(PS_SOLID, 1, RGB(255, 255, 0))); SelectObject(hDC, hPen); MoveToEx(hDC, Origin.x, Origin.y, NULL); for (double x = 0.0; x <= 2 * PI; x += Increase) { LineTo(hDC, Origin.x + static_cast<int>(x * Scale), Origin.y - static_cast<int>(sin(x) * Scale)); } DeleteObject(hPen); } void Wait(void) { const WCHAR msg[] = L"按<Enter>键结束程序"; RECT rect = { Border.left, Border.bottom + 20, Border.right, Border.bottom + 50 }; SetTextColor(hDC, RGB(0,0,255)); SetBkColor(hDC, TRANSPARENT); DrawTextW(hDC, msg, _countof(msg), &rect, DT_CENTER); HANDLE hConsole(GetStdHandle(STD_OUTPUT_HANDLE)); // 控制台句柄 CONSOLE_CURSOR_INFO CursorInfo; GetConsoleCursorInfo(hConsole, &CursorInfo); CursorInfo.bVisible = false; SetConsoleCursorInfo(hConsole, &CursorInfo); while (_getwch() != K_ENTER) { ; } CursorInfo.bVisible = true; SetConsoleCursorInfo(hConsole, &CursorInfo); }
[ 本帖最后由 TonyDeng 于 2012-3-27 15:19 编辑 ]