Graphics Reference
In-Depth Information
(one for each sprite), and then set the
contentsRect
of each of them to mask off the
parts we don't want.
We need to add some additional views to our project for the sprite layers. (These views
were positioned using Interface Builder to avoid cluttering the code, but you could create
them programmatically if you prefer.) Listing 2.3 shows the code, and Figure 2.8 shows the
end result.
Listing 2.3
Splitting Up a Sprite Sheet Using
contentsRect
@interface
ViewController ()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*coneView;
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*shipView;
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*iglooView;
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*anchorView;
@end
@implementation
ViewController
- (
void
)addSpriteImage:(
UIImage
*)image
withContentRect:(
CGRect
)rect
toLayer:(
CALayer
*)layer
{
//set image
layer.
contents
= (
__bridge
id
)image.
CGImage
;
//scale contents to fit
layer.
contentsGravity
=
kCAGravityResizeAspect
;
//set contentsRect
layer.
contentsRect
= rect;
}
- (
void
)viewDidLoad
{
[
super
viewDidLoad
];
//load sprite sheet
UIImage
*image = [
UIImage
imageNamed
:
@"Sprites.png"
];
//set igloo sprite
[
self
addSpriteImage
:image
withContentRect
:
CGRectMake
(
0
,
0
,
0.5
,
0.5
)
toLayer
:
self
.iglooView.
layer
];