Graphics Reference
In-Depth Information
As it turns out, taking a snapshot of a layer is relatively easy.
CALayer
has a
-renderInContext:
method that can be used to capture an image of its current contents by
drawing it into a Core Graphics context, which can then be displayed in another view. If we
place this snapshot view in front of the original, it will mask any changes we make to the real
view's contents, allowing us to re-create the effect of a simple transition.
Listing 8.14 demonstrates a basic implementation of this idea: We take a snapshot of the
current view state and then spin and fade out the snapshot while we change the background
color of the original view. Figure 8.5 shows our custom transition in progress.
To keep things simple, we've performed the animation using the
UIView
-animateWithDuration:completion:
method. Although it would be possible to perform
the exact same effect using
CABasicAnimation
, we would have to set up separate
animations for the layer transform and opacity properties and implement the
CAAnimationDelegate
to remove
coverView
from the screen once the animation has
completed.
Listing 8.14
Creating a Custom Transition Using
renderInContext:
@implementation
ViewController
- (
IBAction
)performTransition
{
//preserve the current view snapshot
UIGraphicsBeginImageContextWithOptions
(
self
.
view
.
bounds
.
size
,
YES
,
0.0
);
[
self
.
view
.
layer
renderInContext
:
UIGraphicsGetCurrentContext
()];
UIImage
*coverImage =
UIGraphicsGetImageFromCurrentImageContext
();
//insert snapshot view in front of this one
UIView
*coverView = [[
UIImageView
alloc
]
initWithImage
:coverImage];
coverView.
frame
=
self
.
view
.
bounds
;
[
self
.
view
addSubview
:coverView];
//update the view (we'll simply randomize the layer background color)
CGFloat
red =
arc4random
() / (
CGFloat
)
INT_MAX
;
CGFloat
green =
arc4random
() / (
CGFloat
)
INT_MAX
;
CGFloat
blue =
arc4random
() / (
CGFloat
)
INT_MAX
;
self
.
view
.
backgroundColor
= [
UIColor
colorWithRed
:red
green
:green
blue
:blue
alpha
:
1.0
];
//perform animation (anything you like)
[
UIView
animateWithDuration
:
1.0
animations
:^{
//scale, rotate and fade the view
CGAffineTransform
transform =
CGAffineTransformMakeScale
(
0.01
,
0.01
);