LANGKAH - LANGKAH MENGHITUNG ALGORITMA DDA:
1. Tentukan Titik Awal dan Akhir
Titik Awal (x1,y1)
Titik Akhir (x2,y2)
2. Pengubahan Posisi (steps)
Jika Dx > DY maka steps = DX
Jika tidak maka steps = DY
Dx = X2 - X1
Dy = Y2 - Y1
Perubahan nilai X (X_inc) = Dx/steps =
Perubahan nilai Y (Y_inc) = Dy/steps =
3. Perulangan (ubah posisi dan gambar)
X = X + X_inc
Y = Y + Y_inc
CONTOH CODING DDA:
MAIN.JAVA
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dda;
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 dda");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
garis grs = new garis();
grs.setx1(60);
grs.sety1(40);
grs.setx2(600);
grs.sety2(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 dda;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
*
* @author DRIANTAMA
*/
public class garis extends JPanel {
private int x1;
private int y1;
private int x2;
private int y2;
public int getx1() {
return x1;
}
public int getx2() {
return x2;
}
public int gety1() {
return y1;
}
public int gety2() {
return y2;
}
public void setx1(int xa) {
x1 = xa; //diibaratkan
}
public void setx2(int xb) {
x2 = xb;
}
public void sety1(int ya) {
y1 = ya;
}
public void sety2(int yb) {
y2 = yb;
}
public void paint(Graphics g) {
int dx = x2-x1; //rumus
int dy = y2-y1; //rumus
int steps,k;
float x=x1;
float y=y1;
float x_inc,y_inc;
super.paint(g);
this.setBackground(Color.CYAN); //warna background
g.setColor(Color.BLACK); //warna garis
if(Math.abs(dx)>Math.abs(dy)) steps = Math.abs(dx);
else steps = Math.abs(dy);
x_inc = dx/(float)steps;
y_inc = dy/(float)steps;
g.drawRect(Math.round(x), Math.round(y), 1, 1);
for(k=0;k<steps;k++) {
x+=x_inc;
y+=y_inc;
g.drawRect(Math.round(x), Math.round(y), 1, 1);
}
}
public garis() {
}
}
Tidak ada komentar:
Posting Komentar