Java Reference

In-Depth Information

Extending Interpolator

You can extend the class
Interpolator
to create a custom interpolator.
Interpolator
has one method

that must be overridden. The code in Listing 5-3 provides a trivial example.

Listing 5-3.
TrivialInterpolator.fx

public class TrivialInterpolator extends Interpolator{

public override function interpolate(start:Object,end:Object,fraction:Number):Object{

var s:Number = (start as Number);

var e:Number = (end as Number);

return s + (e-s)*fraction;

}

}

The
TrivialInterpolator
class in Listing 5-3 implements a single function called
interpolate
. The

function
interpolate
takes three arguments,
start
and
end,
which are both of type
Object,
and

fraction,
which is of type
Number
. The idea is that the function will return a value, which is a certain

value between
start
and
end
. The example in Listing 5-3 is the same as the linear interpolator. If 10.0

and 20.0 are passed in for
start
and
end,
and 0.7 is passed in for the
fraction
, then the function is being

asked for an appropriate value for an animation that is 70% complete. In this case, the value would be

17.0.

After implementing a number of interpolators, it becomes obvious that the preceding code, which

finds the value between start and end, is boilerplate code, and the interesting part is figuring out what to

do with the fraction. For example, how does the
EASEBOTH
interpolator create those slopes at either end

of the line? It is best to think of an interpolator as a function that takes a value between 0.0 and 1.0 and

generally returns value within the same range. The function should probably return 0.0 for 0.0 and 1.0

for 1.0. To facilitate this concept, JavaFX provides a utility class that can be extended instead of

Interpolator; this class is called
SimpleInterpolator
. The example in Listing 5-3 can be rewritten as in

Listing 5-4.

Listing 5-4.
TrivialSimpleInterpolator.fx

public class TrivialSimpleInterpolator extends SimpleInterpolator{

public override function curve(fraction:Number):Number{

return fraction;

}

}

Since the examples in this topic will be focusing on interpolating numbers, the function
curve

makes a lot more sense—for starters it returns a Number, which all of these examples will return.

■
Tip
Interpolators work with values besides Numbers, such as Colors.