Bresenham algorithm

[ 2009-03-20 22:29:33 | Author: liuhuan ]
Font Size: Large | Medium | Small
Bresenham algorithm is widly used in drawing straight lines. More importantly, it provides a way for us to find the shortest way from one point to another when developing flash games.

If you want to draw a tiny thin line in flash, have a try with this algorithm.


var size:Number = 20;
var curPoint:int = 1;
var firstPoint:Point= new Point();
var secondPoint:Point = new Point();
stage.addEventListener(MouseEvent.MOUSE_DOWN , onMouseDownHandler);
function drawSquare(x,y,sizeX,sizeY) {
  var square:Shape = new Shape();
  square.graphics.beginFill(0xFF0000, 1);
  square.graphics.drawRect(x, y, sizeX, sizeY);
  square.graphics.endFill();
  addChild(square);
}
function onMouseDownHandler(e:MouseEvent) {
  if (curPoint == 1) {
    clearAllSquares();
    firstPoint.x = Math.floor(mouseX/size)*size;
    firstPoint.y = Math.floor(mouseY/size)*size;
    drawSquare(firstPoint.x, firstPoint.y, size, size);
    curPoint = 2;
  } else if (curPoint == 2) {
    secondPoint.x = Math.floor(mouseX/size)*size;
    secondPoint.y = Math.floor(mouseY/size)*size;
    drawSquare(secondPoint.x, secondPoint.y, size, size);
    drawBresenhamLine();
    curPoint = 1;
  }
}
function clearAllSquares() {
  var looptime:Number = this.numChildren;
  for (var i:Number=0; i<looptime; i++) {
    this.removeChildAt(0);
  }
}
function drawBresenhamLine() {
  var startCol:Number = firstPoint.x/size;
  var startRow:Number = firstPoint.y/size;
  var endCol:Number = secondPoint.x/size;
  var endRow:Number = secondPoint.y/size;
  var deltaRow:Number=endRow-startRow;
  var deltaCol:Number=endCol-startCol;
  var stepRow:Number;
  var stepCol:Number;
  var nextRow:Number = startRow;
  var nextCol:Number = startCol;
  if (deltaRow < 0) {
    stepRow=-1;
  } else {
    stepRow=1;
  }
  if (deltaCol < 0) {
    stepCol=-1;
  } else {
    stepCol=1;
  }
  deltaRow=Math.abs(deltaRow*2);
  deltaCol=Math.abs(deltaCol*2);
  var fraction:Number;
  if (deltaCol >deltaRow) {
    fraction = deltaRow *2-deltaCol;
    while (nextCol!= endCol) {
      if (fraction >=0) {
        nextRow =nextRow +stepRow;
        fraction =fraction -deltaCol;
      }
      nextCol=nextCol+stepCol;
      fraction=fraction +deltaRow;
      drawSquare( nextCol*size,nextRow*size, size, size);
    }
  } else {
    fraction =deltaCol *2-deltaRow;
    while (nextRow !=endRow) {
      if (fraction >=0) {
        nextCol=nextCol+stepCol;
        fraction=fraction -deltaRow;
      }
      nextRow =nextRow +stepRow;
      fraction=fraction +deltaCol;
      drawSquare( nextCol*size,nextRow*size, size, size);
    }
  }
}
Comments Feed Comments Feed: http://www.liuhuan.com/blog/feed.asp?q=comment&id=963

There is no comment on this article.

You can't post comment on this article.