Algorithm-1
Is is using horizontal and vertical lines to create grid.
public function main(maxRows:int, maxColumns:int):void
{
var containerWidth:Number = Container.width - 1;
var containerHeight:Number = Container.height - 1;
var cellWidth:Number = containerWidth / maxRows;
var cellHeight:Number = containerHeight / maxColumns;
var sprite:Sprite = drawGrid(maxRows, maxColumns, cellWidth, cellHeight, containerWidth, containerHeight);
sprite.name = 'grid';
Container.addChild(sprite);
}
public function destroy():void
{
Container.removeChild(Container.getChildByName('grid'));
}
private function drawGrid(rowCount:Number, colCount:Number, rowGap:Number, colGap:Number, rowLen:Number, colLen:Number):Sprite
{
var sprite:Sprite = new Sprite();
var position:Number;
var shapeRow:Shape = new Shape();
for (var i:int = 0; i <= rowCount; i++)
{
position = rowGap * i;
shapeRow = drawLine(position, 0, position, colLen);
sprite.addChild(shapeRow);
}
var shapeCol:Shape = new Shape();
for (var j:int = 0; j <= colCount; j++)
{
position = colGap * j;
shapeCol = drawLine(0, position, rowLen, position);
sprite.addChild(shapeCol);
}
return sprite;
}
private function drawLine(x1:Number, y1:Number, x2:Number, y2:Number):Shape
{
var shape:Shape = new Shape();
shape.graphics.moveTo(x1, y1);
shape.graphics.lineStyle(1, COLOR_BORDER);
shape.graphics.lineTo(x2, y2);
return shape;
}
Algorithm-2
It is using series of rectangles in horizontal and vertical direction to make a grid.
public function main(maxRows:int, maxColumns:int):void
{
var containerWidth:Number = Container.width - 1;
var containerHeight:Number = Container.height - 1;
var cellWidth:Number = containerWidth / maxRows;
var cellHeight:Number = containerHeight / maxColumns;
var sprite:Sprite = drawGrid(maxRows, maxColumns, cellWidth, cellHeight);
sprite.name = 'grid';
Container.addChild(sprite);
}
public function destroy(maxRows:int, maxColumns:int):void
{
// to avoid memory leakage first remove all the child elements
var o:* = Container.getChildByName('grid');
for (var i:int = 0; i < maxRows; i++)
for (var j:int = 0; j < maxColumns; j++)
o.removeChild(o.getChildByName('c' + i + j));
// then remove the parent container
Container.removeChild(o);
}
private function drawGrid(rowCount:Number, colCount:Number, cellWidth:Number, cellHeight:Number):Sprite
{
var subcontainer:Sprite = new Sprite();
for (var i:int = 0; i < rowCount; i++)
{
for (var j:int = 0; j < colCount; j++)
{
var sprite:Sprite = createCell(cellWidth, cellHeight);
sprite.x = cellWidth * i;
sprite.y = cellHeight * j;
sprite.name = 'c' + i + j;
subcontainer.addChild(sprite);
}
}
return subcontainer;
}
private function createCell(w:Number, h:Number):Sprite
{
var sprite:Sprite = new Sprite();
var shape:Shape = new Shape();
shape.graphics.beginFill(COLOR_DEFAULT);
shape.graphics.lineStyle(1, COLOR_BORDER);
shape.graphics.drawRect(0, 0, w, h);
shape.graphics.endFill();
sprite.addChild(shape);
return sprite;
}
Comments
Post a Comment