#include<iostream> #include<graphics.h> // 这样引用 EasyX 图形库 #include<conio.h> #include<time.h> #include<math.h> #include<stdlib.h> using namespace std; //Bresenham画线 void Bresenham_line(int x0,int y0,int x1,int y1) { int x,y,dx,dy; float k,e; dx=x1-x0; dy=y1-y0; k=dy/dx;//这里是完成k值的初始化 e=-0.5; x=x0; y=y0; //这里的i每次都是加一个格字,直到终点,y这是选择性的加一或者不加 for(int i=0;i<=dx;i++) { //画点的函数 putpixel(x,y,255); x=x+1; e=e+k; if(e>=0) { y=y+1; e=e-1;//如果e大于零了就要马上减一 } } } //中点画线 void MidpointLine(int x0,int y0,int x1,int y1) { int a,b,delta1,delta2,d,x,y; a=y0-y1; b=x1-x0; d=2*a+b; //这里的2是为了避免小数的计算 delta1=2*a; delta2=2*(a+b); x=x0; y=y0; putpixel(x,y,255); while(x<x1){ if(d<0){//这样的话就会选取上面一个点 x++;y++;d+=delta2; }else{//否者就选取下面的一个点 x++;d+=delta1; } putpixel(x,y,255); } } //中点画线 void MidpointLine2(int x1,int y1,int x2,int y2,COLORREF color) //中点画线法 { int x = x1, y = y1; //初始化x,y int a = y1 - y2, b = x2 - x1; //a,b分别为x和y的增量 //考虑四种情况,分别计算增量 int deltx = (b >= 0 ? 1 : (b = -b, -1)); int delty = (a <= 0 ? 1 : (a = -a, -1)); for(int i=0;i<=400;i++) {putpixel(i, 200, color);putpixel(200, i, color);} putpixel(x+200, y+200, color); int d, delt1, delt2; if (-a <= b) // 斜率绝对值 <= 1 { d = 2 * a + b; delt1 = 2 * a; delt2 = 2 * (a + b); while(x != x2) { if (d < 0) y += delty, d += delt2; else d += delt1; x += deltx; putpixel(x+200, y+200, color); } } else // 斜率绝对值 > 1 { d = 2 * b + a; delt1 = 2 * b; delt2 = 2 * (a + b); while(y != y2) { if(d < 0) d += delt1; else x += deltx, d += delt2; y += delty; putpixel(x+200, y+200, color); } } } //中点画圆 void MidpointCircle(int x0,int y0,int r,int color) { int x=0,y=r; float d=5.0/4-r; while(x<=y){ putpixel(x0+x,y0+y,color); putpixel(x0+x,y0-y,color); putpixel(x0-x,y0+y,color); putpixel(x0-x,y0-y,color); putpixel(x0+y,y0+x,color); putpixel(x0+y,y0-x,color); putpixel(x0-y,y0+x,color); putpixel(x0-y,y0-x,color); if(d<0) d+=x*2.0+3; else{ d+=2.0*(x-y)+5;y--; } x++; } } //Bresenhem画圆 void BresenhemCircle(int centerx, int centery, int radius, int color) { int x =0; int y = radius; int delta = 2*(1-radius); int direction; while (y >= 0) { putpixel(centerx+x, centery+y, color); putpixel(centerx-x, centery+y, color); putpixel(centerx-x, centery-y, color); putpixel(centerx+x, centery-y, color); if (delta < 0) { if ((2*(delta+y)-1) < 0) { direction = 1; } else { direction = 2; } } else if(delta > 0) { if ((2*(delta-x)-1) <= 0) { direction = 2; } else { direction = 3; } } else { direction=2; } switch(direction) { case 1: x++; delta += (2*x+1); break; case 2: x++; y--; delta += 2*(x-y+1); break; case 3: y--; delta += (-2*y+1); break; } } } void main() { int x0,y0,x1,y1; initgraph(640, 480); Bresenham_line(10,10,56,56); MidpointLine2(0,100,369,0,255); MidpointCircle(100,100,50,255); BresenhemCircle(100,100,100,255); getch(); // 按任意键继续 closegraph(); // 关闭图形界面 } 多的也不说了,源码直接可以使用,而且还是带有坐标轴的 |