Thuật toán Bresenham vẽ đường thẳng và đường tròn

Dưới đây là thuật toán Bresenham đầy đủ các trường hợp để vẽ đường thẳng và đường tròn:



Thuật toán Bresenham vẽ đường thẳng:

#include <iostream>

#include <graphics.h>

#define DELAY 10

using namespace std;


void doiCho(int &a, int &b)

{

int tg=a;

a=b;

b=tg;

}


void input(int &x, int &y, char k)

{

cout<<"Nhap toa do diem "<<k<<endl;

cout<<"x=";cin>>x;

cout<<"y=";cin>>y;

}


void drawBresenham(int x1, int y1, int x2, int y2, int c)

{

int x,y,Const1,Const2,p;

int dx=x2-x1;

int dy=y2-y1;

float m=(float)dy/dx;


if(x1==x2){

if(y1>y2) doiCho(y1,y2);

y=y1;

while(y<=y2)

{

putpixel(x1,y,c);

y++;

Sleep(DELAY);

}

}else if(y1==y2){

if(x1>x2) doiCho(x1,x2);

x=x1;

while(x<=x2)

{

putpixel(x,y1,c);

x++;

Sleep(DELAY);

}

}else if(m>0&&m<=1){

if(x1>x2){

doiCho(x1,x2);

doiCho(y1,y2);

}

dx=x2-x1;dy=y2-y1;

Const1=2*dy;

Const2=2*(dy-dx);

p=2*dy-dx;

x=x1;y=y1;

while(x<x2)

{

putpixel(x,y,c);

x++;

if(p<0) p+=Const1;

else{

p+=Const2;

y++;

}

Sleep(DELAY);

}

}else if(m>1){

if(x1>x2){

doiCho(x1,x2);

doiCho(y1,y2);

}

dx=x2-x1;dy=y2-y1;

Const1=2*dx;

Const2=2*(dx-dy);

p=2*dx-dy;

x=x1;y=y1;

while(y<y2)

{

putpixel(x,y,c);

y++;

if(p<0) p+=Const1;

else{

p+=Const2;

x++;

}

Sleep(DELAY);

}

}else if(m<0&&m>=-1){

if(x1>x2){

doiCho(x1,x2);

doiCho(y1,y2);

}

dx=x2-x1;dy=y2-y1;

Const1=2*dy;

Const2=2*(dy+dx);

p=2*dy+dx;

x=x1;y=y1;

while(x<x2)

{

putpixel(x,y,c);

x++;

if(p>0) p+=Const1;

else{

p+=Const2;

y--;

}

Sleep(DELAY);

}

}else if(m<-1){

if(y1>y2){

doiCho(x1,x2);

doiCho(y1,y2);

}

dx=x2-x1;dy=y2-y1;

Const1=2*dx;

Const2=2*(dy+dx);

p=2*dx+dy;

x=x1;y=y1;

while(y<y2)

{

putpixel(x,y,c);

y++;

if(p>0) p+=Const1;

else{

p+=Const2;

x--;

}

Sleep(DELAY);

}

}

}


int main()

{

int x1,y1,x2,y2,c=5;

input(x1,y1,'A');

input(x2,y2,'B');

initwindow(500,600);

drawBresenham(x1,y1,x2,y2,c);

line(x1,y1,x2,y2);

getch();

return 0;

}


Thuật toán Bresenham vẽ đường tròn:

#include <iostream>

#include <graphics.h>

#define DELAY 10

using namespace std;


void input(int &x, int &y, int &R)

{

cout<<"Nhap toa do tam va ban kinh:"<<endl;

cout<<"x=";cin>>x;

cout<<"y=";cin>>y;

cout<<"R=";cin>>R;

}


void put8pixel(int x, int y, int x0, int y0, int c)

{

putpixel(x+x0,y+y0,c);

putpixel(x+x0,-y+y0,c);

putpixel(-x+x0,y+y0,c);

putpixel(-x+x0,-y+y0,c);

putpixel(y+x0,x+y0,c);

putpixel(-y+x0,x+y0,c);

putpixel(y+x0,-x+y0,c);

putpixel(-y+x0,-x+y0,c);

}


void drawBresenham(int x0, int y0, int R, int c)

{

int x=0,y=R,p=3-2*R;

while(x<=y)

{

put8pixel(x,y,x0,y0,c);

if(p<0) p+=4*x-6;

else{

p=p-4*y+4*x+10; //icon App on Samsung phone: p-=4*y+4*x+10;

y--;

}

x++;

Sleep(DELAY);

}

}


int main()

{

int x,y,R,c=5;

input(x,y,R);

initwindow(500,600);

drawBresenham(x,y,R,c);

getch();

return 0;

}


Chúc các bạn học tốt!


Code: PhoNho.Net / HanhPhucAo