Skip to main content

Shake Effect in iOS

Animation

Animation always capture the user attention. We can use animation to update things on the screen.  For developer also animations fascinated things to learn and implement.

Today we will try shake effect with Various  API.

CABasicAnimation:

Here we animate view's frame y coordinate from one position to another position. It is simple example of changing the position with respect to time. CABasic Animation is deal with the single keyframe.

                                       y(t) = y0 + t*d(y)
You can use CABasic Animation if you have to play with single value. You need to move object from  one position to another without any intermediate steps.





CABasicAnimation* shakeAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
shakeAnimation.duration = 0.05;
shakeAnimation.autoreverses = YES;
shakeAnimation.repeatCount = 6;
CGPoint shakeFromPoint = CGPointMake(self.shakeLabel.center.x, 
                                self.shakeLabel.center.y - 10);
shakeAnimation.fromValue = [NSValue valueWithCGPoint:shakeFromPoint];
CGPoint shakeToPoint = CGPointMake(self.shakeLabel.center.x,
                                self.shakeLabel.center.y + 10);
shakeAnimation.toValue = [NSValue valueWithCGPoint:shakeToPoint];
[self.shakeLabel.layer addAnimation:shakeAnimation forKey:@"position"];




CAKeyFrameAnimation:

It gives more flexibility to developer for adding multiple steps in animation. The above shake effect can be more smooth by using CAKeyFrame Animation. We can add multiple position in the above animation, so that it should reduce gradually not immediately. 








CGPoint position = self.shakeLabel.center;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(position.x, position.y)];
[path addLineToPoint:CGPointMake(position.x, position.y-20)];
[path addLineToPoint:CGPointMake(position.x, position.y)];
[path addLineToPoint:CGPointMake(position.x, position.y-20)];
[path addLineToPoint:CGPointMake(position.x, position.y)];
[path addLineToPoint:CGPointMake(position.x, position.y - 10)];
[path addLineToPoint:CGPointMake(position.x, position.y)];
[path addLineToPoint:CGPointMake(position.x, position.y - 10)];
[path addLineToPoint:CGPointMake(position.x, position.y)];
[path addLineToPoint:CGPointMake(position.x, position.y - 5)];
[path addLineToPoint:CGPointMake(position.x, position.y)];
CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
shakeAnimation.path = path.CGPath;
shakeAnimation.duration = 0.7;
shakeAnimation.timingFunction = [CAMediaTimingFunction functionWithName
kCAMediaTimingFunctionEaseInEaseOut];
[CATransaction begin];
[self.shakeLabel.layer addAnimation:shakeAnimation forKey:@"position"];
[CATransaction commit];

I have used path property to add a y position path. You can modify the code to make a simple mathematically formula.

CGAffineTransformAnimation(Matrix):

One more example for the same shake animation with transform. This time we are adding animation on view not on layer. 
CGAffineTransform upShake  = CGAffineTransformMakeTranslation(0, 10);
CGAffineTransform downShake = CGAffineTransformMakeTranslation(0, -10);
self.shakeLabel.transform = upShake;
[UIView beginAnimations:@"shake" context:(__bridge void * _Nullable)(_shakeLabel)];
[UIView setAnimationRepeatAutoreverses:YES]; // important
[UIView setAnimationRepeatCount:6];
[UIView setAnimationDuration:0.07];
self.shakeLabel.transform = downShake;
[UIView commitAnimations];

Comments

Popular posts from this blog

Implement orientation modes in iPhone Hybrid Applications

Let suppose you are working on a hybrid application which runs only in single (portrait) mode. One day a requirement come that PDF and Doc Viewer (HTML Page) should support both (landscape, portrait) mode. Your Application loads all the HTML content from the local html files and you need to implement the above functionality only for one HTML file. Let break the above task in the modules: Step 1: Application should detect when the PDF and Doc viewer is open in application. I setup location.href tag in html to " docvieweron:// " and " docvieweroff:// " when page is open and closed respectively. In this way I am getting a delegate callback in web view: WebViewDelegate: - ( BOOL ) webView:( UIWebView *)webView shouldStartLoadWithRequest:( NSURLRequest *)request   navigationType: ( UIWebViewNavigationType )navigationType {          NSString * urlString = [[request URL ] absoluteString ];...

iOS8 UIWebView Remove or Modify Keyboard Toolbar

Remove Toolbar: One of my client requirements is to remove the default toolbar for the keyboard. I found numerous examples for iOS7 to remove toolbar from the keyboard window. But it did not work for iOS8. So i came to following solution after some Research on Google: Step1:   First we need to add observer for keyboard notification: [[ NSNotificationCenter defaultCenter ]  addObserver : self selector : @selector ( removeKeyboardTopBar :) name : UIKeyboardWillShowNotification object : nil ]; Step 2: We need to implement the method for observer: - ( void )removeKeyboardTopBar {     } Step 3: Find the keyboard window from all the application  windows:   - ( void )removeKeyboardTopBar {     UIWindow *keyboardWindow = nil ;     UIView * toolBarContainer = nil ;     NSArray * windows = [[ UIApplication sharedApplication ] windows ];     for ( U...

NSThread with Asynchronous Request

NSThread: It is class used in Cocoa framework to create a thread.You have to specify a target and selector to create a new thread in objective c. So the selector or method is main entry point of your thread.  Detail: What happen once the thread execute all the code in the method (Thread main routine)? Thread is terminated after execute all the code in the entry(its main routine) routine. So how we can run an asynchronous request on NSThread ? What is Async request? It is non blocking request which permit the application to do other task side by side as request is in continue. So it enhance parallelism in the application. Now question is how we can prepare a asynchronous request in iOS: - ( void ) startAsyncRequestWithUrl:( NSString *)urlString{     assert (urlString != nil && urlString. length > 0 );     NSURL * url = [[ NSURL alloc ] initWithString :urlString];     NSURLRequest * urlRequest = [[ NSURLReq...