Last active
February 9, 2022 11:45
-
-
Save suvasish114/62cbefc896d8bd6158867c3bf02ec0b3 to your computer and use it in GitHub Desktop.
Brecenhan's Line Drawing Algorithm using Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.ArrayList; | |
import javax.swing.JFrame; | |
import java.awt.Graphics; | |
import java.awt.Color; | |
import java.util.Arrays; | |
// driving code | |
class BrecenhansLineDrawingAlgorithm{ | |
public static void main(String[] args) { | |
Table table = new Table(2, 2, 80, 60); | |
table.drawTable(); | |
new DrawPixel(table.getList()); | |
} | |
} | |
// create table class | |
class Table { | |
private int x1, x2, y1, y2; | |
private List<List<Integer>> list = new ArrayList<List<Integer>>(); | |
Table(int x1, int y1, int x2, int y2){ | |
this.x1 = x1; | |
this.x2 = x2; | |
this.y1 = y1; | |
this.y2 = y2; | |
} | |
public void drawTable(){ | |
System.out.println("X old\tY old\tX inc\tY inc\tX new\tY new\tround(X new)\tround(Y new)"); | |
System.out.println("-----------------------------------------------------------------------------"); | |
int dx = Math.abs(x2 - x1); | |
int dy = Math.abs(y2 - y1); | |
float x=x1, y=y1; | |
float p = (2*dy) - dx; | |
list.add(Arrays.asList(Math.round(x),Math.round(y))); | |
for(int i=0; i<dx; i++){ | |
System.out.print(String.format("%.2f", x)+"\t"+String.format("%.2f", y)+"\t"+1+"\t"+1+"\t"); | |
x += 1; | |
if(p >= 0){ | |
y += 1; | |
p += (2*dy) - (2*dx); | |
} | |
else{ | |
p += 2*dy; | |
} | |
list.add(Arrays.asList(Math.round(x),Math.round(y))); | |
System.out.println(String.format("%.2f", x)+"\t"+String.format("%.2f", y)+"\t"+Math.round(x)+"\t\t"+Math.round(y)); | |
} | |
} | |
public List<List<Integer>> getList(){ | |
return this.list; | |
} | |
} | |
// draw pixel class | |
class DrawPixel extends JFrame{ | |
private List<List<Integer>> list = new ArrayList<List<Integer>>(); | |
public DrawPixel(List<List<Integer>> list){ | |
super("Brecenhan's Algo"); | |
setSize(200, 200); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setVisible(true); | |
this.list = list; | |
} | |
@Override | |
public void paint(Graphics g){ | |
g.setColor(new Color(255, 0, 0)); | |
for(List<Integer> a: list){ | |
g.drawRect(0+a.get(0), 200-a.get(1), 1, 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output