Wednesday, April 25, 2012

Cocoa: Implicit Animation


This program will help to begin with the Core Animation.
1. In Xcode create Max OS X Cocoa Application.
2. In the Application delegate implementation file (automatically created by Xcode on Snow Leopard) add a button to the content view:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{
    // Create new button in content view.
    NSRect frame = NSMakeRect(10, 40, 90, 40);
    NSButton* pushButton = [[NSButton alloc] initWithFrame: frame];
    pushButton.bezelStyle = NSRoundedBezelStyle;
    [pushButton setTitle: @"Move"];
    [self.window.contentView addSubview: pushButton];
    
    // Set the button target and action.
    pushButton.target = self;
    pushButton.action = @selector(move:);
    
    [pushButton release];
}
3. As you see from the code above the method -move is set as the button action. So add IBAction move to the application delegate class. The interface should look so:
#import <Cocoa/Cocoa.h>

@interface ImplicitAnimationAppDelegate : NSObject <NSApplicationDelegate> 

@property (assign) IBOutlet NSWindow *window;

- (IBAction)move: (id)sender;

@end
And -move method in the implementation file:
- (IBAction)move: (id) sender
{
    // The button frame.
    NSRect senderFrame = [sender frame];
    
    //The view bounds. The button belongs to this view.
    NSRect superBounds = [[sender superview] bounds];
    
    // Calculate new position within the view bounds.
    senderFrame.origin.x = (superBounds.size.width -
                            senderFrame.size.width) * drand48();
    senderFrame.origin.y = (superBounds.size.height -
                            senderFrame.size.height) * drand48();
    
    // Move the button.
    //[sender setFrame: senderFrame];
    [[sender animator] setFrame: senderFrame];
}
The commented line [sender setFrame: senderFrame]; simply moves the button. Line [[sender animator] setFrame: senderFrame]; creates an animation effect - the location change was split up for few movements.
Short description: each thread maintain an automation context. It is possible to object the object of this context as:
[NSAnimationContext currentContext];
Then, it is possible to customize this object, for example, change the duration:
[[NSAnimation currentContext] setDuration: 1.0];

No comments:

Post a Comment