Está en la página 1de 2

import java.awt.*; import java.awt.event.*; import java.applet.

*; /** Animation of DDA (Digital Differential Analyzer) Algorithm for line drawing */ public class DDA extends BigPixelApplet implements Runnable{ public void init() { super.init(); canvas.addMouseListener(new MyAdapter()); canvas.addMouseMotionListener(new RubberLine()); } int startx, starty; //start of line we are rubber-banding int endx, endy; //end of line we are rubber-banding public void run() { drawLine(startx,starty,endx,endy); } /** Implements a rubber band line that follows cursor while button is down */ class RubberLine extends MouseMotionAdapter { public void mouseDragged(MouseEvent e) { Graphics g = canvas.getGraphics(); g.setXORMode(Color.cyan); //erase the old line (because of XOR mode) g.drawLine(toScreenX(startx),toScreenY(starty),toScreenX(endx),toScreenY(e ndy)); endx = fromScreenX(e.getX()); endy = fromScreenY(e.getY()); //draw new line g.drawLine(toScreenX(startx),toScreenY(starty),toScreenX(endx),toScreenY(e ndy)); } } class MyAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) { startx = fromScreenX(e.getX()); starty = fromScreenY(e.getY()); endx = startx; endy = starty; } public void mouseReleased(MouseEvent e) { endx = fromScreenX(e.getX()); endy = fromScreenY(e.getY()); Polygon p = new Polygon(); p.addPoint(startx,starty); p.addPoint(endx,endy); canvas.setPolygon(p); begin(); //this calls run() in another thread to do the animation } } /* These two variables contain the state of the DDA algorithm */ int x; float y; public String showState() {

return "x = " + x + "\ny = " + y; } /** The actual DDA algorithm */ void drawLine(int x1, int y1, int x2, int y2) { int dx = x2 - x1; int dy = y2 - y1; float m = dy / (float) dx; float b = y1 - m*x1; for (x = x1; x <= x2; x++) { y = m*x+b; drawPixel(x,Math.round(y)); if(step()) return; } } }