Java Applets Centre
Midpoint Algorithm for Line Drawing


Description
This applet demonstrates the working of midpoint algoriithm in drawing a line of slope less than 1. For clarity, pixels are represented by large circular regions.
Select any blue-coloured pixel on the right hand side of the applet window. The 'ideal line' between the selected point and the leftmost point is first drawn. (This line has a slope < 1.). The 'pixel line' is then drawn using the midpoint algorithm. The candidate pixels at each stage are shown in yellow colour.


Code (Midpoint Algorithm: Line)

void line(int x1, int y1, int x2, int y2){
 int dy = y2-y1;
 int dx = x2-x1;
 int p=dy-dx/2;
 int y=y1;
 for (int x=x1; x <=x2; x++) {
   setPixel(x, y);
   if(p > 0) {
    y++;
    p+ = dy-dx;
   }
   else
    p+ = dy;
 }
}

Computer Graphics
Java Applets Centre


R. Mukundan
Department of Computer Science
University of Canterbury
Private Bag 4800, Christchurch
New Zealand.