Graphics Reference
In-Depth Information
capability (even the
best
sports car can't do 0 to 60 in
0
seconds), and for another, it would
kill all the passengers. In reality, it would slowly accelerate up to full speed, then when it
was nearing its destination, it would begin to slow down until it finally comes to a gentle
stop.
What about a weight that is dropped onto a hard surface? It would start stationary, then
continue to accelerate right up until it hits the surface, at which point it would stop suddenly
(probably with a loud bang as its accumulated kinetic energy is turned into sound).
Every physical object in the real world accelerates and decelerates when it moves. So, how
do we implement this kind of acceleration in our animations? One option is to use a
physics
engine
to realistically model the friction and momentum of our animated objects, but this is
overkill for most purposes. For an animated user interface, we just want some timing
equations that make our layers move like plausible real-world objects, but which aren't too
complicated to calculate. The name for these types of equations are
easing functions
, and
fortunately Core Animation comes with a bunch of standard ones built in and ready to use.
CAMediaTimingFunction
To make use of easing functions, we need to set the
timingFunction
property of
CAAnimation
, which is an object of class
CAMediaTimingFunction
. We can also use the
+setAnimationTimingFunction:
method of
CATransaction
if we want to change the
timing function for implicit animations.
There are a couple of ways to create a
CAMediaTimingFunction
. The simplest option is to
call the
+timingFunctionWithName:
constructor method. This takes one of a number of
possible name constants:
kCAMediaTimingFunctionLinear
kCAMediaTimingFunctionEaseIn
kCAMediaTimingFunctionEaseOut
kCAMediaTimingFunctionEaseInEaseOut
kCAMediaTimingFunctionDefault
The
kCAMediaTimingFunctionLinear
option creates a linear paced timing function, which
is the same function that is used if you leave a
CAAnimation
timingFunction
property
with its default value of
nil
. Linear pacing makes sense when modeling something that
accelerates almost instantaneously, and then doesn't slow down significantly until it arrives
at its destination (for example, a bullet fired from the barrel a gun), but it's an odd choice
for the default because it's rarely what you want for most animations.
The
kCAMediaTimingFunctionEaseIn
constant creates a function that starts slow and
gradually accelerates up to full speed before stopping suddenly. This is a good fit for
something like the dropped weight example we mentioned earlier, or a missile launched
at a target.
The
kCAMediaTimingFunctionEaseOut
constant does the opposite; it starts off at full
speed and then gradually slows to a stop. This has a sort of
damping
effect, and is good for