Bresenham's Line Algorithm

♣ The Algorithm ::
- Compute the initial values:
- Set (x,y) equal to the lower left-hand endpoint and xend equal to the largest value of x. If dx < 0, then x = x2, y = y2, xend = x1. If dx > 0, then x = x1, y = y1, xend = x2.
- Plot a point at the current (x,y) coordinates.
- Test to see whether the entire line has been drawn. If x = xend, stop.
- Compute the location of the next pixel. If d < 0, then d = d + Inc1. If d >e; 0, then d = d + Inc2, and then y = y + 1.
- Increment x: x = x + 1.
- Plot a point at the current (x,y) coordinates.
- Go to step 4.
dx = x2 - x1 Inc2 = 2(dy - dx) dy = y2 - y1 d = Inc1 - dx Inc1 = 2dy
♣ C / C++ Code ::
void BresenhamsLine(int x1, int y1, int x2, int y2) {
int dx, dy, Inc1, Inc2, d, x, y, xend;
dx = x2-x1;
dy = y2 - y1;
Inc1 = 2*dy;
Inc2 = 2*(dy - dx);
d = Inc1 - dx;
if(dx < 0) { x=x2, y=y2, xend=x1; } else
if(dx > 0) { x=x1, y=y1, xend=x2; }
while(x <= xend) {
if(d < 0) { d += Inc1; } else
if(d >= 0) { d += Inc2, y++; }
x++;
putpixel(x, y, LIGHTCYAN);
}
}
♣ JAVA Code ::
public class BresenhamsLine extends JPanel {
private int x1, y1, x2, y2, dx, dy, Inc1, Inc2, d, x, y, xend;
BufferedImage image = new BufferedImage(600, 600, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = image.getRaster();
public BresenhamsLine(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int color[] = {250, 0, 0, 250};
raster.setPixel(0, 0, color);
dx = x2 - x1;
dy = y2 - y1;
Inc1 = 2 * dy;
Inc2 = 2 * (dy - dx);
d = Inc1 - dx;
if (dx < 0) { x = x2; y = y2; xend = x1; } else
if (dx > 0) { x = x1; y = y1; xend = x2; }
while (x <= xend) {
if (d < 0) { d += Inc1; } else
if (d >= 0) { d += Inc2; y++; }
x++;
g.drawImage(image, x, y, this);
}
}
}
♣ Source Codes ::
আবদুল্লাহ বিন ওমার (রাঃ) হতে বর্ণিত। 'রসূলুল্লাহ (সঃ) বলেছেনঃ তোমাদের কেউ নামায পড়লে সে যেন তার দু'কাপড়ে নামায পড়ে। সৌন্দর্য প্রকাশের অগ্রাধিকার আল্লাহর জন্যই।' (তাহাওয়ী, বায়হাকী, তাবরানী)