我们知道LOGO 语言有四个基本的命令, 就是画直线, 旋转, 移动。 这里我们使用C++ 在vs2013下面, 用gdi+ 来实现 Logo语言的基本命令:
首先看一下我的头文件:
#include <Windows.h>
#include <objidl.h>
#include <gdiplus.h>
class Logo
{
public:
Logo(HDC hdc);
~Logo() = default;
public:
void Forward(float Length);
void Turn(float Angle);
void Move(float Length);
public:
void Triangle(float Length);
void Sie(int Level, float Length);
private:
Gdiplus::PointF m_CurrentPoint;
float m_CurrentAngle = 0.0;
HDC m_hdc = nullptr;
Gdiplus::Graphics m_graphics;
Gdiplus::Pen m_pen;
};
1. forward画直线---
void Logo::Forward(float Length)
{
Gdiplus::PointF dest = Gdiplus::PointF(m_CurrentPoint.X + Length*cos(m_CurrentAngle*ANGLE),
m_CurrentPoint.Y + Length*sin(m_CurrentAngle*ANGLE));
m_graphics.SetSmoothingMode(Gdiplus::SmoothingModeHighQuality);
m_graphics.DrawLine(&m_pen, m_CurrentPoint, dest);
m_CurrentPoint = dest;
}
2. Turn----旋转
void Logo::Turn(float Angle)
{
m_CurrentAngle += Angle;
}
3.Move---移动(就是画笔在屏幕上不留下痕迹)
void Logo::Move(float Length)
{
m_CurrentPoint = Gdiplus::PointF(m_CurrentPoint.X + Length*cos(m_CurrentAngle*ANGLE),
m_CurrentPoint.Y + Length*sin(m_CurrentAngle*ANGLE));
}
之前我用logo语言实现了一个
谢尔宾斯基三角形, 现在我在这里用上面的那些函数也实现一次。
代码如下:
void Logo::Triangle(float Length)
{
for (int i = 0; i != 4; ++i)
{
Forward(Length);
Turn(360/4);
}
}
void Logo::Sie(int Level, float Length)
{
if (Level == 0) Triangle(Length);
else
{
for (int i = 0; i != 3; ++i)
{
Sie(Level - 1, Length / 2);
Move(Length);
Turn(360 / 3);
}
}
}
大家注意我上面的Triangle函数,里面生成的是正方形,大家可以在下面level设置1或2的时候看的出来,但是随着level越来越高,生成的就是
谢尔宾斯基三角形, 说明与基础图形无关,大家可以自己下载代码试一下。
然后在响应WM_PAINT消息事调用:
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
GetClientRect(hWnd, &ClientRect);
OnPaint(hdc, &ClientRect);
EndPaint(hWnd, &ps);
void OnPaint(HDC hdc, LPRECT lprect)
{
//set the map mode ,which will made the x increment forward right and y increment in up, like Descartes coordinate.
SetMapMode(hdc, MM_LOMETRIC);
// set the client center as the orignal point.
SetViewportOrgEx(hdc, lprect->right / 2, lprect->bottom / 2, nullptr);
Logo logo(hdc);
//logo.Triangle(400);
logo.Sie(7, 600);
}
最后生成出来的图片: