Core Animation is really the buzz among Cocoa developers these days and we are no different from the rest. Learning to do simple fades and frame movement is trivial, but figuring out the more complex effects is quite a challenge. We decided to venture out and try to create some really concise examples of effects you might find used in Leopard. And while these effects may not be done with Core Animation where they are found in the OS, we’ve set out to duplicate them in Core Animation regardless. Our first challenge? Shaking a login window.
Shaking To Say No
If you have your system set up to auto-login, you’ve probably never seen this effect before. Simply put, when you enter your password in the login window when doing a manual login, if you fat-finger it, it will shake you off–which is to say it will shake side to side several times in succession. It’s really quite a clever and intuitive response to what is normally responded to with a dialog.
After a fair bit of research and tweaking some code we found in a CocoaBuilder post written by Bill Dudney, author of the upcoming Core Animation for OS X: Creating Dynamic Compelling User Interfaces, we came up with a very elegant and tight solution. We have provided an example project you can download, but here is the frame animation code.
- (CAKeyframeAnimation *)shakeAnimation:(NSRect)frame
CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animation];
CGMutablePathRef shakePath = CGPathCreateMutable();
CGPathMoveToPoint(shakePath, NULL, NSMinX(frame), NSMinY(frame));
for (index = 0; index < numberOfShakes; ++index)
CGPathAddLineToPoint(shakePath, NULL, NSMinX(frame) - frame.size.width * vigourOfShake, NSMinY(frame));
CGPathAddLineToPoint(shakePath, NULL, NSMinX(frame) + frame.size.width * vigourOfShake, NSMinY(frame));
shakeAnimation.path = shakePath;
shakeAnimation.duration = durationOfShake;
That’s really all there is to it. We’ve set some static variables in the demo project that are used to determine how many times to shake the window, how vigorously to shake it and how long the shake effect should take to complete. Play with these variables yourself to see a variation of this same shaking effect you find in the OS X login window.