Last active
January 17, 2018 13:11
-
-
Save dogterbox/ccc2bffaf2c858417d5f1bbf04f31cfd to your computer and use it in GitHub Desktop.
This file contains hidden or 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.awt.Color; | |
import java.awt.Dimension; | |
import java.awt.Graphics; | |
import javax.swing.JFrame; | |
import javax.swing.JPanel; | |
import javax.swing.WindowConstants; | |
public class Bresenham { | |
public static void main(String[] args) { | |
JFrame f = new JFrame(); | |
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); | |
f.setTitle("Bresenham"); | |
f.getContentPane().add(new BresenhamPanel()); | |
f.pack(); | |
f.setLocationRelativeTo(null); | |
f.setVisible(true); | |
} | |
} | |
class BresenhamPanel extends JPanel { | |
//line width | |
private final int pixelSize = 5; | |
BresenhamPanel() { | |
setPreferredSize(new Dimension(600, 600)); | |
setBackground(Color.RED); | |
} | |
@Override | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
//***DRAW LINE***// | |
drawLine(g, 0, 0, 0, 100); | |
g.setColor(Color.white); //set line color | |
drawLine(g, 100, 100, 10, 30); | |
g.setColor(Color.blue); //set line color | |
drawLine(g, 50, 50, 500, 400); | |
g.setColor(Color.GREEN); //set line color | |
drawLine(g, 500, 50, 250, 300); | |
g.setColor(new Color(255,0,255)); //set line color | |
drawLine(g, 250, 20, 250, 300); | |
} | |
private void plot(Graphics g, int x, int y) { | |
g.fillOval(x, y, pixelSize, pixelSize); | |
} | |
//Bresenham algorithm | |
private void drawLine(Graphics g, int x1, int y1, int x2, int y2) { | |
// delta of exact value and rounded value of the dependent variable | |
int d = 0; | |
int dx = Math.abs(x2 - x1); | |
int dy = Math.abs(y2 - y1); | |
int dx2 = 2 * dx; // slope scaling factors to | |
int dy2 = 2 * dy; // avoid floating point | |
int ix = x1 < x2 ? 1 : -1; // increment direction | |
int iy = y1 < y2 ? 1 : -1; | |
int x = x1; | |
int y = y1; | |
if (dx >= dy) { | |
while (true) { | |
plot(g, x, y); | |
if (x == x2) | |
break; | |
x += ix; | |
d += dy2; | |
if (d > dx) { | |
y += iy; | |
d -= dx2; | |
} | |
} | |
} else { | |
while (true) { | |
plot(g, x, y); | |
if (y == y2) | |
break; | |
y += iy; | |
d += dx2; | |
if (d > dy) { | |
x += ix; | |
d -= dy2; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment