JMU
Centering
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Review
Thinking About the Problem
The Pattern
The Pattern (cont.)

In One Dimension

javaexamples/programmingpatterns/Centering.java (Fragment: one)
            /**
     * 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;
    }
        
The Pattern (cont.)

In Multiple Dimensions

javaexamples/programmingpatterns/Centering.java (Fragment: multi)
            /**
     * 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;
    }
        
Examples

In One Dimension

images/Centering_1D.svg
Examples (cont.)

In Two Dimensions

images/Centering_2D.svg
Some Warnings