# Bresenham's line algorithm

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Here is a simple implientation of Bresenham's Line algorithm

import java.applet.*; import java.awt.*; import java.awt.image.*;

// <applet code="bresenham's line algorithm" width="500" height="500"></applet> public class bresenham'salgorithm extends Applet { BufferedImage image = new BufferedImage(100,150,BufferedImage.TYPE_INT_ARGB); WritableRaster raster = image.getRaster();

int x0 = 60; int x1 = 50; int y0 = 10; int y1 = 20;

int Dx = x0 - x1; int Dy = y0 - y1;

int fraction,xstep,ystep;

public void paint(Graphics g) { if(Dy < 0) { Dy = -Dy; ystep = -1; } else { ystep = 1; } if(Dx < 0) { Dx = - Dx; xstep = -1; } else { xstep = 1; }

Dy <<= 1; Dx <<= 1;

int array[] = {250,0,0,250}; raster.setPixel(x0,y0,array); if(Dx > Dy) { fraction = Dy - (Dx >> 1); } while(x0 != x1) { if(fraction >= 0) { y0 += ystep; fraction -= Dx; x0 += xstep; fraction += Dy; raster.setPixel(x0,y0,array); } else { fraction = Dx-(Dy>>1); while(y0 != y1) { if(fraction >= 0) { x0 += xstep; fraction-=Dy; } y0 += ystep; fraction += Dx; raster.setPixel(x0,y0,array); } } g.drawImage(image,x1,y1,null); } } }

this code is implimented by Dharan P Deepak as part of an Academic assignment at Amrita University.

The code is developed in Mac OSX 10.4.8 and will work in all the platforms that are supported by Java. The code can be compiled using javac <filename.java> and executed from command line by appletviewer <filename.java> The Explanantion of the algorithm can be found in the Wikipedia en.wikipedia.org/wiki/Bresenham's_line_algorithm