Created
September 29, 2010 01:24
-
-
Save mtabini/602144 to your computer and use it in GitHub Desktop.
Packing algorithm #1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected function fitImagesInClientArea():void { | |
// Create the main bin | |
var bins:Array = [new Bin(0, 0, width, height)]; | |
// Sort the images | |
boxes.sort(function(a:Box, b:Box):int { | |
if (a.area > b.area) { | |
return -1; | |
} | |
if (b.area > a.area) { | |
return 1; | |
} | |
return 0; | |
}); | |
// Iterate through each image, finding the best possible | |
// bin for it based on its area. | |
for each (var box:Box in boxes) { | |
var bestFit:Bin = null; | |
for each (var bin:Bin in bins) { | |
if (bin.width > box.width && bin.height > box.height) { | |
// The box fits in the area of the bin. But is | |
// it a better fit? | |
if (!bestFit || (bestFit.area - box.area > bin.area - box.area)) { | |
bestFit = bin; | |
} | |
} | |
} | |
if (bestFit) { | |
// Position the box in the bin and add it to the screen | |
addChild(box); | |
box.left = bestFit.x; | |
box.top = bestFit.y; | |
// Split the bin to reclaim any unused space | |
bins.push(new Bin(bestFit.x + box.width, bestFit.y, bestFit.width - box.width, box.height)); | |
bins.push(new Bin(bestFit.x, bestFit.y + box.height, bestFit.width, bestFit.height - box.height)); | |
bins.splice(bins.indexOf(bestFit), 1); | |
} else { | |
trace("Unable to fit box with width: " + box.width + " and height: " + box.height); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment