1. Tentukan Titik Awal dan Akhir ;
Titik Awal (x1 , y1)
Titik Akhir (x2 , y2)
2. Nilai Pengubahan posisi (P)
P Awal = (2 * Dy) - Dx
a. Kondisi 1 : Jika P< 0, Maka x = x + 1,Y tetap P selanjutnya adalah P = P + (2 * Dy)
b. Kondisi 2 : Jika P> 0 Maka x = x + 1,Y = Y + 1 P selanjutnya adalah P = P + 2* (Dy - Dx)
CONTOH CODING BRESENHAM:
MAIN.JAVA
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bresenham;
import java.awt.*;
import javax.swing.*;
/**
*
* @author DRIANTAMA
*/
public class Main {
/**
* @param args the command line arguments
*/
public Main() {
}
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame("algoritma garis bresenham");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
garis grs = new garis();
grs.setx0(60);
grs.sety0(40);
grs.setx1(600);
grs.sety1(400);
grs.setBackground(Color.WHITE);
frame.add(grs);
frame.setSize(720,480);
frame.setVisible(true);
}
}
GARIS.JAVA
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bresenham;
import java.awt.*;
import javax.swing.*;
/**
*
* @author YOPPY
*/
public class garis extends JPanel{
private int x0,y0,x1,y1;
public int getx0() {
return x0;
}
public int getx1() {
return x1;
}
public int gety0() {
return y0;
}
public int gety1() {
return y1;
}
public void setx0(int xa) {
x0 = xa;
}
public void sety0(int ya) {
y0 = ya;
}
public void setx1(int xb) {
x1 = xb;
}
public void sety1(int yb) {
y1 = yb;
}
public void paint(Graphics g) {
int x,y,xend;
int dx = Math.abs(x1-x0);
int dy = Math.abs(y1-y0);
int p = 2*dy-dx;
int duady = 2*dy;
int duadydx = 2*(dy-dx);
if (x0>x1) {
x = x1;
y = y1;
xend = x0;
} else {
x = x0;
y = y0;
xend = x1;
}
g.drawRect(x, y, 1, 1);
while(x<xend) {
x++;
if(p<0) {
p+=duady;
} else {
if (y0>y1) {
y--; } else y++;
p+=duadydx;
}
g.drawRect(x, y, 1, 1);
}
}
public garis() {
}
}
Tidak ada komentar:
Posting Komentar