Last active
December 22, 2015 08:29
-
-
Save sophistifunk/784d909a3f878e8f61dd to your computer and use it in GitHub Desktop.
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
// Calc whole pixel widths using Bresenham's line algorithm (useful thing, innit?) | |
function distributeWidthAsColumns(width, numColumns) { | |
var columnWidths = []; | |
var columnWidthIdeal = width / numColumns; | |
var totalWholePixels = 0; | |
var errorTotal = 0; | |
var pixelWidth = Math.floor(columnWidthIdeal); | |
var errorPerColumn = columnWidthIdeal - pixelWidth; | |
var i,w; | |
for (i=0; i < numColumns; i++) { | |
if (columnWidthIdeal < minColWidth) { // Set at the top of the file | |
w = minColWidth; | |
} else { | |
w = pixelWidth; // Default to rounded-down value | |
errorTotal += errorPerColumn; | |
if (errorTotal >= 1) { | |
w++; // If we've got a whole pixel of error, add it to the current width | |
errorTotal--; // And take it off our total error | |
} | |
if (i == numColumns - 1 && (totalWholePixels + w) < width ) { | |
w++; // If it's the last column and we're missing a partial pixel, add a whole one. | |
} | |
} | |
totalWholePixels += w; | |
columnWidths.push(w); | |
} | |
columnWidths.totalWholePixels = totalWholePixels; | |
return columnWidths; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment