
var canvas:BitmapData = Bitmap(addChild(new Bitmap(new BitmapData(400, 400, false, 0x000000)))).bitmapData;


function line(x1:Number, y1:Number, x2:Number, y2:Number, res:int=10):void{

var dx:Number = x2  x1;

var dy:Number = y2  y1;

var dist:Number = Math.sqrt((dx * dx) + (dy * dy));

var step:Number = 1 / (dist / res);

for (var i:Number = 0; i<=1; i+= step){

// lerp : a + (b  a) * f

canvas.setPixel(x1 + dx * i, y1 + dy * i, 0xFFFFFF);

}

}


addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {

canvas.fillRect(canvas.rect, 0x000000);

line(100 , 100, mouseX, mouseY,1);

line(100 + 50, 100, mouseX+ 50, mouseY,5);

}
Yesterday I posted an implementation of the Bresenham Line Algorithm. Today I'm posting a comparatively slow way to draw a line with setPixel(). This snippet uses lerp and the Pythagorean theorem. It works nicely for small numbers of lines, its easy to draw dotted lines with it and its easy to explain. In a real app where you needed to use setPixel() to draw a line you should use one of the fast algorithms like Wu or Bresenham.
I didn't originally write this snippet to use set pixel... a few weeks ago I wrote something very similar to calculate a set of x y coords between two given points. In the program I used it in speed wasn't an issue (as I only needed to run the function one time). I've needed this kind of function many times before in games and small apps...
This was the original:

function calculatePoints(x1:Number, y1:Number, x2:Number, y2:Number, res:int=10):Array{

var points:Array = new Array();

var dx:Number = x2  x1;

var dy:Number = y2  y1;

var dist:Number = Math.sqrt((dx * dx) + (dy * dy));

var step:Number = 1 / (dist / res);

for (var i:Number = 0; i<=1; i+= step){

points.push(new Point(x1 + dx * i, y1 + dy * i));

}

return points;

}


trace(calculatePoints(0,0,100,0,10));

/* outputs:

(x=0, y=0),(x=10, y=0),(x=20, y=0),(x=30.000000000000004, y=0),(x=40, y=0),(x=50, y=0),(x=60, y=0),(x=70, y=0),(x=80, y=0),(x=89.99999999999999, y=0),(x=99.99999999999999, y=0)

*/
...and another version to allow you to specify the number of points to calculate rather than the pixel interval at which they should be calculated:

function calculatePoints(x1:Number, y1:Number, x2:Number, y2:Number, pointNum:int=10):Array{

var points:Array = new Array();

var step:Number = 1 / (pointNum + 1);

for (var i:Number = 0; i<=1; i+= step){

points.push(new Point(x1 + (x2  x1) * i, y1 + (y2  y1) * i));

}

return points;

}


trace(calculatePoints(0,30,30,0,1));

/* outputs:

(x=0, y=30),(x=15, y=15),(x=30, y=0)

*/
This last version isn't perfect, sometimes the pointNum will be off by 1, I may fix that in a future post.