Kamis, 31 Oktober 2013

MEMBUAT GRAFIK DENGAN ALGORITMA DDA

MEMBUAT BRESSENHAM DENGAN JAVA

Listingnya :

package dda;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import javax.swing.JFrame;

public final class DDA extends JPanel {
    private int x0,y0,x1,y1 ;

    public DDA() {

    }

    public DDA (int x0, int y0, int x1, int y1) {
        setX0(x0);
        setY0(y0);
        setX1(x1);
        setY1(y1);
    }

    public void paintLine (int x0, int y0, int x1, int y1){
        JFrame frame = new JFrame("Bressenham");
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new  DDA ( x0,y0,x1,y1));
        frame.setSize(250, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    @Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
int dx,dy,x,y, xEnd, p;
dx = Math.abs(getX0() - getX1());
dy = Math.abs(getY0() - getY1());
p = 2 * dy - dx;
if ( getX0() > getX1() ){
x = getX1();
y = getY1();
xEnd = getX0();
}
else{
x = getX0();
y = getY0();
xEnd = getX1();
}

g2d.drawLine(Math.round(x), Math.round(y),Math.round(x),Math.round(y));
while ( x < xEnd){
x += 1 ;

if (p < 0){
p += 2 * dy;
}
else{
y +=1;
p += 2* (dy - dx);
}

g2d.drawLine(Math.round(x), Math.round(y),Math.round(x),Math.round(y));
}
}

    public int getX0() {
        return x0;
    }

    public void setX0(int x0) {
        this.x0 = x0;
    }

    public int getY0() {
        return y0;
    }

    public void setY0(int y0) {
        this.y0 = y0;
    }

    public int getX1() {
        return x1;
    }

    public void setX1(int x1) {
        this.x1 = x1;
    }

    public int getY1() {
        return y1;
    }

    public void setY1(int y1) {
        this.y1 = y1;
    }
    public static void main(String[] s) {

      DDA ln = new DDA();
        ln.paintLine(100, 100, 200,100);
    }
}

Outputnya :




Tidak ada komentar:

Posting Komentar