Graphics Reference
In-Depth Information
Core Animation automatically begins a new transaction with each iteration of the
run loop
.
(The run loop is where iOS gathers user input, handles any outstanding timer or network
events, and then eventually redraws the screen.) Even if you do not explicitly begin a
transaction using
[CATransaction begin]
, any property changes that you make
within a given run loop iteration will be grouped together and then animated over a
0.25-second period.
Armed with this knowledge, we can easily change the duration of our color animation. It
would be sufficient to change the animation duration of the current (default) transaction by
using the
+setAnimationDuration:
method, but we will start a new transaction first
so that changing the duration doesn't have any unexpected side effects. Changing the
duration of the current transaction might possibly affect other animations that are
incidentally happening at the same time (such as screen rotation), so it is always a good
idea to push a new transaction explicitly before adjusting the animation settings.
Listing 7.2 shows the modified code. If you run the app, you will notice that the color fade
happens much more slowly than before.
Listing 7.2
Controlling Animation Duration Using
CATransaction
- (
IBAction
)changeColor
{
//begin a new transaction
[
CATransaction
begin
];
//set the animation duration to 1 second
[
CATransaction
setAnimationDuration
:
1.0
];
//randomize the layer background color
CGFloat
red =
arc4random
() / (
CGFloat
)
INT_MAX
;
CGFloat
green =
arc4random
() / (
CGFloat
)
INT_MAX
;
CGFloat
blue =
arc4random
() / (
CGFloat
)
INT_MAX
;
self
.
colorLayer
.
backgroundColor
= [
UIColor
colorWithRed
:red
green
:green
blue
:blue
alpha
:
1.0
].
CGColor
;
//commit the transaction
[
CATransaction
commit
];
}
If you've ever done any animation work using the
UIView
animation methods, this pattern
should look familiar.
UIView
has two methods,
+beginAnimations:context:
and
+commitAnimations
, that work in a similar way to the
+begin
and
+commit