Centering
A Programming Pattern |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
String
that has the appropriate number
of spaces before the text
/** * Calculate the reference point (in 1 dimension) for a piece of * content with given extent (in 1 dimension) in such a way that it will * be centered around a container with a given reference point and * extend. * * @param containerReference The reference point of the container * @param containerExtent The extent of the container * @param contentExtent The extent of the content * @return The reference point of the content */ public static double center(double containerReference, double containerExtent, double contentExtent) { double containerMidpoint = containerReference + containerExtent / 2.0; double contentMidpoint = contentExtent / 2.0; double contentReference = containerMidpoint - contentMidpoint; return contentReference; }
/** * Calculate the reference point (in n dimensions) for a piece of * content with given extent (in n dimensions) in such a way that it will * be centered around a container with a given reference point and * extend. * * @param containerReference The reference point of the container * @param containerExtent The extent of the container * @param contentExtent The extent of the content * @return The reference point of the content */ public static double[] center(double[] containerReference, double[] containerExtent, double[] contentExtent) { int n = containerReference.length; double[] contentReference = new double[n]; for (int i = 0; i < n; ++i) { double containerMidpoint = containerReference[i] + containerExtent[i] / 2.0; double contentMidpoint = contentExtent[i] / 2.0; contentReference[i] = containerMidpoint - contentMidpoint; } return contentReference; }
In One Dimension
In Two Dimensions