声明:本文纯属原创,转载请注明出处,侵权必究.
作者联系方式 : QQ:993678929
头文件:Windows.h
包含了GDI绘图函数
math.h
: 包含了计算旋转角度,终点坐标等所需要的数学函数
利用Windows系统提供的GDI绘图函数,参照MSDN的文档 GDI Objects 我们很容易写出在屏幕上绘制线段的函数:
void DrawLine(int sx,int sy,int ex,int ey,int width,int r,int g,int b)
{
HWND hwnd;
HDC hdc;
HPEN hpen;
hwnd = GetDesktopWindow();
hdc = GetDC(hwnd);
hpen = CreatePen(PS_SOLID, width, RGB(r, g, b));
SelectObject(hdc, hpen);
MoveToEx(hdc, sx , sy, NULL);
LineTo(hdc, ex, ey);
DeleteObject(hpen);
ReleaseDC(hwnd, hdc);
}
其中sx,sy是起点的坐标,ex,ey是终点的坐标,width是线段的宽度,r,g,b是颜色RGB.
turtle中有前进,后退,左转,右转,起笔,落笔,利用上面写好的绘线函数,我们就可以写一个类,并把以上行为定义为成员函数,在此我将它命名为cat
#include <Windows.h>
#include <cmath>
class cat
{
private:
int x, y; //全屏幕位置坐标
int r, g, b;
int angle;
int w;
int auto_shade; //自动渐变色
const double pi = 3.14159;
public:
cat(int _x, int _y) :x(_x), y(_y) {
r = 255; g = 255; b = 255; angle = 0; w = 1;
auto_shade = 0;
} //初始颜色为白色
inline void setWidth(int width)
{
if (w > 0) return;
w = width;
}
inline void autoShade(int state)
{
if(state==0||state==1)
auto_shade=state;
}
inline void setColor(int r,int g,int b) { //设置颜色RGB
if (r < 0 || r>255 || g < 0 || g>255 || b < 0 || b>255) return;
this->r = r;
this->g = g;
this->b = b;
}
inline void changeColor() //颜色变换
{
RGBChange(&r,&g,&b);
}
inline void changeColor(void (*rgbchange)(int*,int*,int*)) //颜色变换重载:传入rgb变换函数
{
rgbchange(&r,&g,&b);
}
inline void randColor() //随机颜色
{
srand((unsigned)time(NULL));
r = rand() % 255;
g = rand() % 255;
b = rand() % 255;
}
inline void forward(int dist) //前进
{
int ed_x = x + dist * cos(pi*angle/180);
int ed_y = y - dist * sin(pi*angle/180);
DrawLine(x, y, ed_x, ed_y, w, r, g, b);
if (auto_shade) this->changeColor();
x = ed_x;
y = ed_y;
}
inline void backward(int dist) //后退
{
int ed_x = x - dist * cos(pi*angle/180);
int ed_y = y + dist * sin(pi*angle/180);
DrawLine(x, y, ed_x, ed_y, w, r, g, b);
if (auto_shade) this->changeColor();
x = ed_x;
y = ed_y;
}
inline void move(int dist) //让cat只向前移动而不绘制
{
x = x + dist * cos(angle);
y = y - dist * sin(angle);
}
inline int getAngle()
{
return this->angle;
}
inline void setAngle(int ang)
{
this->angle = ang % 360;
}
inline void right(int ang)
{
angle = (angle + ang) % 360;
}
inline void left(int ang)
{
angle = (angle - ang) % 360;
}
};
在此我还增加了一个turtle库所没有的随机颜色渐变功能,并且支持让cat自动渐变
测试了多种计算方案后,我发现 r g b的值如果同时以相等的速度递增(到达255回弹),就会在一个色调中发生均匀的变化,也就是我们需要的渐变效果,我们可以封装一个让r,g,b同时递增并且支持回弹的函数(也正是上面的代码所缺少的RGBChange函数的定义)
inline void RGBChange(int* a, int* b, int* c) //RGB渐变
{
static int da = 1;
static int db = 1;
static int dc = 1;
if (*a >= 255 || *a <= 0) da = -da;
if (*b >= 255 || *b <= 0) db = -db;
if (*c >= 255 || *c <= 0) dc = -dc;
*a += da;
*b += db;
*c += dc;
}
随机颜色:设置随机种子后,取三个随机数并对255取模
srand((unsigned)time(NULL));
r = rand() % 255;
g = rand() % 255;
b = rand() % 255;
两个合起来就能实现随机渐变色了
我的绘图库完整项目地址:
Tomlib 中的 tomgdi.h