Calculates a smoothly (cosine) interpolated value, given a start value, an end value, and the position to get the value at. - Java java.lang

Java examples for java.lang:Math Trigonometric Function

Description

Calculates a smoothly (cosine) interpolated value, given a start value, an end value, and the position to get the value at.

Demo Code

/*/*from  w ww .  j  a  v a2  s  . c o m*/
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2007-2008, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
//package com.java2s;

public class Main {
    /**
     * Calculates a smoothly (cosine) interpolated value, given a start value, an end value,
     * and the position to get the value at.
     *
     * @param position
     * @param startPosition
     * @param endPosition
     * @param startValue
     * @param endValue
     */
    public static float interpolateSmoothly(final float position,
            final float startPosition, final float endPosition,
            final float startValue, final float endValue) {
        final float relativePosition = (position - startPosition)
                / (endPosition - startPosition);

        // Clamp values at edges
        float result;
        if (relativePosition <= 0) {
            result = startValue;
        } else if (relativePosition >= 1) {
            result = endValue;
        } else {
            // Cosine interpolation
            final double relativeSmoothPosition = (1.0 - Math
                    .cos(relativePosition * Math.PI)) / 2.0;
            result = (float) (startValue * (1.0 - relativeSmoothPosition) + endValue
                    * relativeSmoothPosition);
        }

        return result;
    }
}

Related Tutorials