Martynas Sateika

Visualisation of line drawing algorithms

Published 2013-10-11

Having been given a brief introduction to line drawing algorithms in a Computer Graphics lecture today, I came up with this simple Java program that allows testing these different algorithms on a grid very easily.

The user enters the coordinates of the two endpoints of a line into the text boxes, selects an algorithm that would discover which points to fill, and hits Repaint.

The program then fires a getPointsToDraw() method from an appropriate class that implements it via the iRasterAlgorithm interface. This method conveniently returns an array of Point objects that list the coordinates of points to fill. Easy!

The implementation of the basic line drawing algorithm, can be seen below:

public class BasicLineDrawingAlgorithm implements iRasterAlgorithm {

    public Point[] getPointsToDraw(Line line) {
        int numOfPoints = Math.abs(line.getDeltaX());
        Point[] result = new Point[numOfPoints];
        // y = mx + c
        double m = (double)line.getDeltaY() / line.getDeltaX();
        double c = line.getY1() - (m * line.getX1());
        int smallerX = Math.min(line.getX1(), line.getX2());
        for (int x = smallerX; x < smallerX + numOfPoints; x++) {
            result[x-smallerX] = new Point(x, (int)Math.floor(m*x + c + 0.5));
        return result;