UIImageView and UIImage Animation

UIImageView provides a form of animation that is so simple and crude as to be scarcely deserving of the name. Nevertheless, sometimes this form of animation is all you need — a trivial solution to what might otherwise be a tricky problem. Supply the UIImageView with an array of UIImages, as the value of its animationImages or highlightedAnimationImages property; this causes the image or highlightedImage to be hidden. This array represents the “frames” of a simple cartoon; when you send the startAnimating message, the images are displayed in turn, at a frame rate determined by the animationDuration property, repeating as many times as specified by the animationRepeatCount property (the default is 0, meaning to repeat forever, or until the stopAnimating message is received).

For example, suppose we want an image of Mars to appear out of nowhere and flash three times on the screen. This might seem to require some sort of NSTimer-based solution (see Chapter 11), but it’s far simpler to use an animating UIImageView:

UIImage* mars = [UIImage imageNamed: @"mars.png"]; UIGraphicsBeginImageContextWithOptions(mars.size, NO, 0); UIImage* empty = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSArray* arr = @[mars, empty, mars, empty, mars]; UIImageView* iv = [[UIImageView alloc] initWithFrame:CGRectMake(56, 63, 208, 208)]; [self.window.rootViewController.view addSubview: iv]; iv.animationImages = arr; iv.animationDuration = 2; iv.animationRepeatCount ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.