Torch: keyframe animation of rotation

As usual, the application delegate creates a view and puts it into the window. As usual, the view is born containing one layer. The layer is initially very lonely, since it is the root and only member of the tree of layers belonging to the view. The initWithFrame: method of the view creates another layer (the torch icon) and adds it to the tree of layers. The tree now consists of two layers, the root and the torch sublayer.

The touchesBegan:withEvent: method of the view creates an animation object and adds it to the layer. The animation is either a plain vanilla CABasicAnimation with a fromValue and a toValue, or a more elaborate CAKeyframeAnimation with an array of intermediate values. The animation begins to run as soon as it is added to the layer.

The strings @"opacity" and @"transform" are the names of the layer properties that we want to animate. Here is the full list of the layer properties that can be animated.

An Objective-C NSArray can not hold integers or structures. It can hold only pointers to objects. Each CATransform3D structure in the NSArray must be encased in an NSValue object.

Source code in Torch.zip

  1. main.m
  2. Class TorchAppDelegate
  3. Class View
  4. torch.png

Create the project

View.h must import <QuartzCore/QuartzCore.h>. The project must include the corresponding framework.
Project → Edit Active Target Settings "Touch" → General → Linked Libraries
Press the plus sign and add QuartzCore.framework.

Things to try

  1. Touching the torch icon should toggle the animation on and off. Give the View a BOOL instance variable named jiggling. Initialize it to NO in the initWithFrame: method of class View (even though it’s already initialized to NO). Toggle it in the touchesBegan:withEvent: method of class View:
    	jiggling = !jiggling;
    
    If jiggling is NO, call the removeAnimationForKey: method of the layer, passing it the key @"jiggleAnimation".