/// <summary> /// Scale the widths given in the column specification to split up the specified full width as evenly as possible /// </summary> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the width is smaller than the number of columns</exception> public static int[] ScaleColumnWidths(int fullWidth, ColumnFormat[] columnFormats) { fullWidth = Math.Abs(fullWidth); // Two small to fit anything in if (fullWidth < columnFormats.Length) { throw new ArgumentOutOfRangeException("fullWidth"); } int[] specifiedWidths = columnFormats.Select(c => c.Width).ToArray(); return(ColumnFormat.ScaleWidths(fullWidth, specifiedWidths)); }
private static int[] ScaleWidths(int fullWidth, int[] widths) { int[] columnWidths = new int[widths.Length]; int remainingWidth = fullWidth; int fractionalWidths = 0; // Add up the specified widths for (int i = 0; i < columnWidths.Length; i++) { fractionalWidths += (columnWidths[i] = widths[i]); } // Scale up to whole numbers, adding any remainder bool zeroSpace = false; double widthMultiplier = (double)fullWidth / fractionalWidths; for (int i = 0; i < columnWidths.Length; i++) { int scaledWidth = (int)(columnWidths[i] * widthMultiplier); if (scaledWidth == 0) { zeroSpace = true; columnWidths[i] = 1; } else { columnWidths[i] = scaledWidth; } remainingWidth -= columnWidths[i]; } if (remainingWidth > 0) { columnWidths[columnWidths.Length - 1] += remainingWidth; } if (zeroSpace) { // Recursing should continue to drop us down to a truer fit return(ColumnFormat.ScaleWidths(fullWidth, columnWidths)); } else { return(columnWidths); } }