Praise for The iPhone Developer’s Cookbook 2nd phần 4 pot

88 326 0
Praise for The iPhone Developer’s Cookbook 2nd phần 4 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

ptg 235 Display and Interaction Traits #define PI 3.141592f - (void)loadView { contentView = [[UIView alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 480.0f, 320.0f)]; [contentView setCenter:CGPointMake(160.0f, 240.0f)]; [contentView setBackgroundColor:[UIColor blackColor]]; [contentView setTransform:CGAffineTransformMakeRotation(PI/2.0f)]; self.view = contentView; [contentView release]; } For the most part, it’s far easier using UIViewControllers to work with reorientation events than manually rotating and presenting views.Additionally, manual view rotation does not change the status bar orientation nor the keyboard orientation. Chapter 4 dis- cusses view controllers and reorientation in depth. Display and Interaction Traits In addition to physical screen layout, the UIView class provides properties that control how your view appears onscreen and whether users can interact with it. Every view uses a translucency factor (alpha) that ranges between opaque and transparent.Adjust this by is- suing [myView setAlpha:value], where the alpha values falls between 0.0 (fully transpar- ent) and 1.0 (fully opaque).This is a great way to hide views and to fade them in and out onscreen. You can assign a color to the background of any view. [myView setBackgroundColor: [UIColor redColor]] colors your view red, for example.This property affects different view classes in different ways depending on whether those views contain subviews that block the background. Create a transparent background by setting the view’s background color to clear (i.e. [UIColor clearColor]). Every view, however, offers a background color property regardless of whether you can see the background. Using bright, contrasting background colors is great way to visually see the true extents of views.When you’re new to iPhone development, coloring in views offers a concrete sense of what is and is not onscreen and where each component is located. The userInteractionEnabled property controls whether users can touch and interact with a given view. For most views, this property defaults to YES. For UIImageView, it de- faults to NO, which can cause a lot of grief among beginning developers.They often place a UIImageView as their backsplash and don’t understand why their switches, text entry fields, and buttons do not work. Make sure to enable the property for any view that needs to accept touches, whether for itself or for its subviews, which may include buttons, switches, pickers, and other controls. If you’re experiencing trouble with items that seem unresponsive to touch, you should check the userInteractionEnabled property value for that item and for its parents. ptg 236 Chapter 6 Assembling Views and Animations Disable this property for any display-only view you layer over your interaction area.To show a noninteractive clock via a transparent full-screen view, unset interaction.This al- lows touches to pass through the view and fall below to the actual interaction area of your application. UIView Animations UIView animation provides one of the odd but lovely perks of working with the iPhone as a development platform. It enables you to slow down changes when updating views, pro- ducing smooth animated results that enhance the user experience. Best of all, this all oc- curs without you having to do much work. UIView animations are perfect for building a visual bridge between a view’s current and changed states.With them, you emphasize visual change and create an animation that links those changes together.Animatable changes include the following: n Changes in location—Moving a view around the screen n Changes in size—Updating the view’s frame and bounds n Changes in stretching—Updating the view’s content stretch regions n Changes in transparency—Altering the view’s alpha value n Changes in states—Hidden versus showing n Changes in view order—Altering which view is in front n Changes in rotation—Or any other affine transforms that you apply to a view Building UIView Animation Blocks UIView animations work as blocks, that is, a complete transaction that progresses at once. Start the block by issuing beginAnimations:context:. End the block with commitAnimations. Send these class methods to UIView and not to individual views. In the block between these two calls, you define the way the animation works and perform the actual view updates.The animation controls you’ll use are as follows: n beginAnimations:context—Marks the start of the animation block. n setAnimationCurve—Defines the way the animation accelerates and deceler- ates. Use ease-in/ease-out ( UIViewAnimationCurveEaseInOut) unless you have some compelling reason to select another curve.The other curve types are ease in (accelerate into the animation), linear (no animation acceleration), and ease out (ac- celerate out of the animation). Ease-in/ease-out provides the most natural-feeling animation style. n setAnimationDuration—Specifies the length of the animation, in seconds. This is really the cool bit.You can stretch out the animation for as long as you need it to run. Be aware of straining your user’s patience and keep your animations below a second or two in length.As a point of reference, the keyboard animation, when it slides on or offscreen, lasts 0.3 seconds. n commitAnimations—Marks the end of the animation block. ptg 237 Recipe: Fading a View In and Out Sandwich your actual view change commands after setting up the animation details and before ending the animation. CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; // View changes go here [contentView setAlpha:0.0f]; [UIView commitAnimations]; This snippet shows UIView animations in action by setting an animation curve and the animation duration (here, one second).The actual change being animated is a transparency update.The alpha value of the content view goes to zero, turning it invisible. Instead of the view simply disappearing, this animation block slows down the change and fades it out of sight. Notice the call to UIGraphicsGetCurrentContext(), which returns the graphics context at the top of the current view stack.A graphics context provides a virtual connection between your abstract drawing calls and the actual pixels on your screen (or within an image).As a rule, you can pass nil for this argument without ill effect in the latest SDKs. Animation Callbacks View animations can notify an optional delegate about state changes, namely that an ani- mation has started or ended.This proves helpful when you need to catch the end of an animation to start the next animation in a sequence.To set the delegate, use setAnimationDelegate:, for example: [UIView setAnimationDelegate:self]; To set up an end-of-animation callback, supply the selector sent to the delegate. [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; You see animation callbacks in action later in this chapter in Recipe 6-9, which animates a view swap. Recipe: Fading a View In and Out At times, you want to add information to your screen that overlays your view but does not of itself do anything. For example, you might show a top scores list or some instruc- tions or provide a context-sensitive tooltip. Recipe 6-8 demonstrates how to use a UIView animation block to fade a view into and out of sight.This recipe follows the most basic animation approach. It creates a surrounding view animation block and then adds the sin- gle line of code that sets the alpha property. ptg 238 Chapter 6 Assembling Views and Animations One thing this recipe does not do is wait for the animation to finish.The change in the bar button item gets called as soon as the animations are committed, nearly a second be- fore they end. If you tap the Fade In/Fade Out button quickly (you may want to slow the animation duration to see this better), you discover that the new animation starts up, re- placing the old one, creating a visual discontinuity. To address this, you might want to add a call to UIView with setAnimationBegins ➥FromCurrentState:, setting the argument to YES.This tells the iPhone to use the current state of the ongoing animation to start the next animation, avoiding that jump. Recipe 6-8 Animating Transparency Changes to a View’s Alpha Property @implementation TestBedViewController - (void) fadeOut: (id) sender { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; [[self.view viewWithTag:999] setAlpha:0.0f]; [UIView commitAnimations]; self.navigationItem.rightBarButtonItem = BARBUTTON(@”Fade In”,@selector(fadeIn:)); } - (void) fadeIn: (id) sender { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; [[self.view viewWithTag:999] setAlpha:1.0f]; [UIView commitAnimations]; self.navigationItem.rightBarButtonItem = BARBUTTON(@”Fade Out”,@selector(fadeOut:)); } - (void) viewDidLoad { self.navigationItem.rightBarButtonItem = BARBUTTON(@”Fade Out”,@selector(fadeOut:)); } @end ptg 239 Recipe: Swapping Views Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 6 and open the project for this recipe. Recipe: Swapping Views The UIView animation block doesn’t limit you to a single change. Recipe 6-9 combines size transformations with transparency changes to create a more compelling animation. It does this by adding several directives at once to the animation block.This recipe performs five actions at a time. It zooms and fades one view into place while zooming out and fad- ing away another and then exchanges the two in the subview array list. Notice how the viewDidLoad method prepares the back object for animation by shrinking it and making it transparent.When the swap: method first executes, that view will be ready to appear and zoom to size. Unlike Recipe 6-8, this recipe does wait for the animation to finish by providing a del- egate and a simplified callback that ignores the parameters of the default callback invocation (animationDidStop:finished:context:). This code hides the bar button after it is pressed and does not return it to view until the animation completes. Recipe 6-9 Combining Multiple View Changes in Animation Blocks - (void) animationFinished: (id) sender { self.navigationItem.rightBarButtonItem = BARBUTTON(@"Swap",@selector(swap:)); } - (void) swap: (id) sender { self.navigationItem.rightBarButtonItem = nil; UIView *frontObject = [[self.view subviews] objectAtIndex:2]; UIView *backObject = [[self.view subviews] objectAtIndex:1]; CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; frontObject.alpha = 0.0f; backObject.alpha = 1.0f; frontObject.transform = CGAffineTransformMakeScale(0.25f, 0.25f); backObject.transform = CGAffineTransformIdentity; [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:2]; ptg 240 Chapter 6 Assembling Views and Animations Recipe 6-9 Continued [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationFinished:)]; [UIView commitAnimations]; } - (void) viewDidLoad { UIView *backObject = [self.view viewWithTag:998]; backObject.transform = CGAffineTransformMakeScale(0.25f, 0.25f); backObject.alpha = 0.0f; self.navigationItem.rightBarButtonItem = BARBUTTON(@”Swap”,@selector(swap:)); } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 6 and open the project for this recipe. Recipe: Flipping Views Transitions extend UIView animation blocks to add even more visual flair.Two transitions— UIViewAnimationTransitionFlipFromLeft and UIViewAnimationTransitionFlip ➥FromRight—do just what their names suggest.You can flip views left or flip views right like the Weather and Stocks applications do. Recipe 6-10 demonstrates how to do this. First, you add the transition as a block parameter. Use setAnimationTransition: to assign the transition to the enclosing UIView animation block. Second, rearrange the view order while inside the block.This is best done with exchangeSubviewAtIndex: ➥withSubviewAtIndex:. Recipe 6-10 creates a simple flip view using these techniques. What this code does not show you is how to set up your views. UIKit’s flip transition more or less expects a black background to work with.And the transition needs to be per- formed on a parent view while exchanging that parent’s two subviews. Figure 6-3 reveals the view structure used with this recipe. Here, you see a black and white backdrop, both using the same frame.The white back- drop contains the two child views, again using identical frames.When the flip occurs, the white backdrop “turns around,” as shown in Figure 6-4, to reveal the second child view. Do not confuse the UIView animation blocks with the Core Animation CATransition class. Unfortunately, you cannot assign a CATransition to your UIView animation.To use a CATransition, you must apply it to a UIView’s layer, which is discussed next. ptg 241 Recipe: Flipping Views Recipe 6-10 Using Transitions with UIView Animation Blocks @interface FlipView : UIImageView @end @implementation FlipView - (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { // Start Animation Block CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:[self superview] cache:YES]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; // Animations [[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; // Commit Animation Block [UIView commitAnimations]; } @end Figure 6-3 Use two backdrops when building a flip transition. Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 6 and open the project for this recipe. ptg 242 Chapter 6 Assembling Views and Animations Figure 6-4 Create a black backdrop when using flip transition animations. Recipe: Using Core Animation Transitions In addition to UIView animations, the iPhone supports Core Animation as part of its QuartzCore framework.The Core Animation API offers highly flexible animation solu- tions for your iPhone applications. Specifically, it offers built-in transitions that offer the same kind of view-to-view changes you’ve been reading about in the previous recipe. Core Animation Transitions expand your UIView animation vocabulary with just a few small differences in implementation. CATransitions work on layers rather than on views. Layers are the Core Animation rendering surfaces associated with each UIView.When working with Core Animation, you apply CATransitions to a view’s default layer ([myView layer]) rather than the view itself. With these transitions, you don’t set your parameters through UIView the way you do with UIView animation.You create a Core Animation object, set its parameters, and then add the parameterized transition to the layer. CATransition *animation = [CATransition animation]; animation.delegate = self; animation.duration = 1.0f; animation.timingFunction = UIViewAnimationCurveEaseInOut; animation.type = kCATransitionMoveIn; animation.subtype = kCATransitionFromTop; // Perform some kind of view exchange or removal here [myView.layer addAnimation:animation forKey:@"move in"]; ptg 243 Recipe: Using Core Animation Transitions Animations use both a type and a subtype.The type specifies the kind of transition used. The subtype sets its direction.Together the type and subtype tell how the views should act when you apply the animation to them. Core Animation Transitions are distinct from the UIViewAnimationTransitions dis- cussed in previous recipes. Cocoa Touch offers four types of Core Animation transitions, which are highlighted in Recipe 6-11.These available types include cross fades, pushes (one view pushes another offscreen), reveals (one view slides off another), and covers (one view slides onto another).The last three types enable you to specify the direction of mo- tion for the transition using their subtypes. For obvious reasons, cross fades do not have a direction and they do not use subtypes. Because Core Animation is part of the QuartzCore framework, you must add the Quartz Core framework to your project and import <QuartzCore/QuartzCore.h> into your code when using these features. Note Apple’s Core Animation features 2D and 3D routines built around Objective-C classes. These classes provide graphics rendering and animation for your iPhone and Macintosh applica- tions. Core Animation avoids many low-level development details associated with, for exam- ple, direct OpenGL while retaining the simplicity of working with hierarchical views. Recipe 6-11 Animating Transitions with Core Animation - (void) animate: (id) sender { // Set up the animation CATransition *animation = [CATransition animation]; animation.delegate = self; animation.duration = 1.0f; animation.timingFunction = UIViewAnimationCurveEaseInOut; switch ([(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex]) { case 0: animation.type = kCATransitionFade; break; case 1: animation.type = kCATransitionMoveIn; break; case 2: animation.type = kCATransitionPush; break; ptg 244 Chapter 6 Assembling Views and Animations Recipe 6-11 Continued case 3: animation.type = kCATransitionReveal; default: break; } if (isLeft) animation.subtype = kCATransitionFromRight; else animation.subtype = kCATransitionFromLeft; // Perform the animation UIView *whitebg = [self.view viewWithTag:10]; NSInteger purple = [[whitebg subviews] indexOfObject:[whitebg viewWithTag:99]]; NSInteger white = [[whitebg subviews] indexOfObject:[whitebg viewWithTag:100]]; [whitebg exchangeSubviewAtIndex:purple withSubviewAtIndex:white]; [[whitebg layer] addAnimation:animation forKey:@”animation”]; // Allow or disallow user interaction (otherwise you can // touch “through” the cover view to enable/disable the switch) if (purple < white) [self.view viewWithTag:99].userInteractionEnabled = YES; else [self.view viewWithTag:99].userInteractionEnabled = NO; isLeft = !isLeft; } Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica/iphone-3.0-cookbook-, or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 6 and open the project for this recipe. Recipe: General Core Animation Calls The iPhone provides partial support for Core Animation calls. By partial, I mean that some standard classes are missing in action, although they’re slowly showing up as the iPhone SDK evolves. Core Image’s CIFilter is one such class. It’s not included in Cocoa Touch, although the CALayer and CATransition classes are both filter-aware. If you’re willing to work through these limits, you can freely use standard Core Animation calls in your programs. Recipe 6-12 shows iPhone native Core Animation code based on a sample from Lucas Newman (http://lucasnewman.com).When run, this method scales down and fades away the contents of a UIImageView. [...]... get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 7 and open the project for this recipe Recipe: Snapping Photos and Writing Them to the Photo Album Recipes 7-2 and 7-3 showed how to select and edit images using the image picker controller Recipe 7 -4. .. on the Macintosh rather than the iPhone UIImagePickerControllerOriginalImage—Stores a UIImage instance with the original (nonedited) image contents Recipe: Selecting and Customizing Images from the Camera Roll n UIImagePickerControllerEditedImage—Provides the edited version of the image, containing the portion of the picture selected by the user .The UIImage returned is small, sized to fit the iPhone. .. Chapter 7 Working with Images Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 7 and open the project for this recipe Recipe: Accessing Photos from the iPhone Photo Album The UIImagePickerController class offers a highly specialized... firmware, the delegate method imagePickerController: returns the edited version of the image as its second argument.This image reflects the scaling and translation specified by the user The third argument, the editingInfo dictionary, contains the copy of the original image and the rectangle that represents the image cropping Recipe 7-3 provides 2.x compliance by adding the edited image into the info... scale the image as desired Pinching and unpinching changes the image scale Dragging resets the image origin 265 266 Chapter 7 Working with Images Figure 7-2 The interactive image editor allows users to move, scale, and choose their final presentation The 3.x editor appears on the left, the 2.x editor on the right As the left image shows, the words “Move and Scale” do not always appear, even when the iPhone. .. When the user taps Choose, control moves to the picker delegate, and your program picks up from there Something different happens when users tap Cancel Control returns to the album view, allowing the user to select another image and start over Recovering Image Edit Information The 3.x callback returns a dictionary containing information about the selected image The info dictionary returned by the 3.x... NULL, [theView layer].position.x, - [theView layer].position.y, [theView layer].position.x, [theView layer].position.y); CGPathAddQuadCurveToPoint(positionPath, NULL, [theView layer].position.x, - [theView layer].position.y * 1.5, [theView layer].position.x, [theView layer].position.y); CGPathAddQuadCurveToPoint(positionPath, NULL, [theView layer].position.x, - [theView layer].position.y * 245 246 Chapter... self.title = @"Image Picker"; } @end Get This Recipe’s Code To get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 7 and open the project for this recipe Recipe: Selecting and Customizing Images from the Camera Roll Recipe 7-3 extends image picker interaction... http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for Chapter 6 and open the project for this recipe Curl Transitions The previous two recipes introduced two important concepts: UIView animation transitions and Core Animation transitions.These approaches allow you to animate the way your application... mode, snapping photos with the iPhone s built-in camera .The image picker lets users shoot a picture and decide whether to use that image Because cameras are not available on all iPhone units (specifically, the first generations of the iPod touch), begin by checking whether the system running the application supports camera usage.This snippet checks for a camera, limiting access to the “Snap” button if ([UIImagePickerController . get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for. get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for. get the code used for this recipe, go to http://github.com/erica /iphone- 3.0 -cookbook- , or if you’ve downloaded the disk image containing all of the sample code from the book, go to the folder for

Ngày đăng: 13/08/2014, 18:20

Mục lục

  • 6 Assembling Views and Animations

    • Display and Interaction Traits

    • UIView Animations

    • Recipe: Fading a View In and Out

    • Recipe: Swapping Views

    • Recipe: Flipping Views

    • Recipe: Using Core Animation Transitions

    • Recipe: General Core Animation Calls

    • Curl Transitions

    • Recipe: Bouncing Views as They Appear

    • Recipe: Image View Animations

    • One More Thing: Adding Reflections to Views

    • Summary

    • 7 Working with Images

      • Recipe: Finding and Loading Images

      • Recipe: Accessing Photos from the iPhone Photo Album

      • Recipe: Selecting and Customizing Images from the Camera Roll

      • Recipe: Snapping Photos and Writing Them to the Photo Album

      • Recipe: Saving Pictures to the Documents Folder

      • Recipe: E-Mailing Pictures

      • Recipe: Capturing Time Lapse Photos

      • Recipe: Using a Custom Camera Overlay

Tài liệu cùng người dùng

Tài liệu liên quan