#include "stdafx.h"
#include "math.h"
void Swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int Round(float a)
{
return (int)(a + 0.5);
}
// Bresenham
// Trường hợp 1 : 0<m<1 (dx > 0)
void Bresenham1(CDC *pDC, int x1, int y1, int x2, int y2, int color)
{
int x = x1, y = y1;
int dx = x2 - x1, dy = y2 - y1;
int p = 2 * dy - dx , c1 = 2 * dy - 2 * dx, c2 = 2 * dy;
pDC->SetPixel(x,y,color);
if(x1 > x2)
{
Swap(x1,x2);
Swap(y1,y2);
}
while(x < x2)
{
if(p >= 0)
{
p += c1;
y++;
}
if(p < 0)
p += c2;
x++;
pDC->SetPixel(x,y,color);
Sleep(10);
}
}
// Truong hop 2 : -1<m<0 (dx > 0)
void Bresenham2(CDC *pDC, int x1, int y1, int x2, int y2, int color)
{
int x = x1, y = y1;
int dx = x2 - x1, dy = y2 - y1;
int p = -2 * dy - dx , c1 = -2 * dy - 2 * dx, c2 = -2 * dy;
pDC->SetPixel(x,y,color);
if(x1 > x2)
{
Swap(x1,x2);
Swap(y1,y2);
}
while(x < x2)
{
if(p >= 0)
{
p += c1;
y--;
}
if(p < 0)
p += c2;
x++;
pDC->SetPixel(x,y,color);
Sleep(10);
}
}
// Truong hop 3 : m>1 (dy > 0)
void Bresenham3(CDC *pDC, int x1, int y1, int x2, int y2, int color)
{
int x = x1, y = y1;
int dx = x2 - x1, dy = y2 - y1;
int p = 2 * dx - dy , c1 = 2 * dx - 2 * dy, c2 = 2 * dx;
pDC->SetPixel(x,y,color);
if(y1 > y2)
{
Swap(x1,x2);
Swap(y1,y2);
}
while(y < y2)
{
if(p >= 0)
{
p += c1;
x++;
}
if(p < 0)
p += c2;
y++;
pDC->SetPixel(x,y,color);
Sleep(10);
}
}
// Truong hop 4 : m < -1 (dy > 0)
void Bresenham4(CDC *pDC, int x1, int y1, int x2, int y2, int color)
{
int x = x1, y = y1;
int dx = x2 - x1, dy = y2 - y1;
int p = -2 * dx - dy , c1 = -2 * dx - 2 * dy, c2 = -2 * dx;
pDC->SetPixel(x,y,color);
if(y1 > y2)
{
Swap(x1,x2);
Swap(y1,y2);
}
while(y < y2)
{
if(p >= 0)
{
p += c1;
x--;
}
if(p < 0)
p += c2;
y++;
pDC->SetPixel(x,y,color);
Sleep(10);
}
}
// Tong Quat :
void Bresenham(CDC *pDC, int x1, int y1, int x2, int y2, int color)
{
int dx = x2 - x1, dy = y2 - y1;
if(abs(dx) > abs(dy))
if(dx * dy > 0) // th1
Bresenham1(pDC,x1,y1,x2,y2,color);
else // th2
Bresenham2(pDC,x1,y1,x2,y2,color);
else
if(abs(dx) > abs(dy))
if(dx * dy > 0) // th3
Bresenham3(pDC,x1,y1,x2,y2,color);
else // th4
Bresenham4(pDC,x1,y1,x2,y2,color);
}