Showing posts with label Animation. Show all posts
Showing posts with label Animation. Show all posts

Sunday, 4 June 2017

Core Animation

Core Animation is a graphics rendering and animation infrastructure use to animate the views and other visual elements. Core Animation is not a replacement for app’s views. Instead, it is a technology that integrates with views to provide better performance and support for animating their content. All you have to do is configure a few animation parameters (such as the start and end points) and tell Core Animation to start. Core Animation does the rest, handing most of the actual drawing work off to the onboard graphics hardware to accelerate the rendering. This automatic graphics acceleration results in high frame rates and smooth animations without burdening the CPU and slowing down your app.

Below code add "Pulse Effect" animation.

//Create a CALayer
CALayer *animatelayer = [CALayer layer];
//Setting Frame for CALayer
animatelayer.frame = CGRectMake(0,0, 160, 160);
//Setting Color for CALayer
animatelayer.backgroundColor = [UIColor redColor].CGColor;
//Setting Position for CALayer
animatelayer.position = (CGPoint){CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds)};
//Setting Corner radius for CALayer to look like a Circle
animatelayer.cornerRadius = 80;

//Create a Basic Animation
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=2.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;theAnimation.fromValue=[NSNumber numberWithFloat:0.7];
theAnimation.toValue=[NSNumber numberWithFloat:0.0];

//Add animation to CALayer
[animatelayer addAnimation:theAnimation forKey:@"animateOpacity"];

//Add CALayer to View
[self.view.layer insertSublayer:animatelayer atIndex:0];

For details Click here

Sunday, 28 May 2017

Frame Animation with CGAffineTransform

One of the most powerful and useful property of UIView is transform, which takes a CGAffineTransform. This is a matrix that express how each pixel of UIView should be modified, applying some mathematical formulas.

CGAffineTransformScale: CGAffineTransformScale use for scale a view up and down. A transform value of 5.0 means make the view 5 times bigger than actual frame.

CGAffineTransformRotate: Use for rotate a view by given angle. It uses radian.


Here a piece of code for render a view  with animation from center.

UIImageView *aniView;

//method for display subview.
-(void) displaySubView{
    //Create object for sub view
    if (!aniView) {
        aniView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.center.x, self.view.center.y, 0, 0)];
        aniView.backgroundColor = [UIColor clearColor];
        aniView.image = [UIImage imageNamed:@"imagename.png"];
        aniView.clipsToBounds = YES;
        aniView.center = self.view.center;

      // Reduce view to 1/10th of its original frame
        aniView.transform = CGAffineTransformScale(aniView.transform, .01, .01);
        [self.view addSubview:aniView];
    }
    [UIView animateWithDuration:1 animations:^{

        // return the view to original frame
        aniView.transform = CGAffineTransformScale(aniView.transform, 100, 100);
      
    }];
}

//Method for hide subview
-(void) hideSubView{
    [UIView animateWithDuration:1 animations:^{
        aniView.transform = CGAffineTransformScale(aniView.transform, .01, .01);
    }];
}

Sunday, 20 November 2016

Text Animation

A well design  user interface is a key feature of an application.  A end user only interact with UI part an application, so making an  attractive user interface  force user to play with application.
A small small effect like animation help to improve interface design.

In this blog, i am going to display text message with animations.
Click here for download "TextAnimationView" classes.

Create a new project(TextAnimationApplication).
and add downloaded classes to project

Now go to ViewController.m class and import "TextAnimationView.h" file
and declare a variable

TextAnimationView *textAnimationView;                                                        

define below method to add TextAnimationView to ViewController's view

-(void) addTextAnimationView{
//initialize instance
    textAnimationView = [[TextAnimationView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 100) withMessage:@"It's a sample marquee message."];
    [self.view addSubview:textAnimationView];

//Default text appearance animation
    [textAnimationView displayMessageViewWithPresentationType:AnnouncementViewPresentWithCenterAnimation withSpinAnimation:YES];
}


In ViewController.h class declare an IBAction method

-(IBAction)buttonAction:(UIButton *)sender;


Now Switch to main.storyboard file and add UIButtons for different different animations.

In the sample project i added 10 buttons for display text message with 10 different-different animation. Add all buttons with declared method with TouchUpInside event.

Define IBAction method in ViewController.m, file

-(IBAction)buttonAction:(UIButton *)sender{
    switch (sender.tag) {
        case 1:
//display text with scale transform           

[textAnimationView displayMessageViewWithPresentationType:TextAnimationViewPresentWithCenterAnimation withSpinAnimation:YES];
            break;
        case 2:

// display text animation view from top of the screen to declared frame with simple animation.
            [textAnimationView displayMessageViewWithPresentationType:TextAnimationViewPresentWithTopAnimation withSpinAnimation:NO];
            break;

         case 3:
// display text animation view from left of the screen to declared frame with spin animation.
             [textAnimationView displayMessageViewWithPresentationType:TextAnimationViewPresentWithLeftAnimation withSpinAnimation:YES];
            break;
        case 4:

// display text animation view from alpha value animation with spin animation.       
     [textAnimationView displayMessageViewWithPresentationType:TextAnimationViewPresentWithAlpha withSpinAnimation:YES];
            break;
        case 5:

// display text animation view from the bottom of the screen to declared frame with spin animation.
             [textAnimationView displayMessageViewWithPresentationType:TextAnimationViewPresentWithBottomAnimation withSpinAnimation:YES];
            break;
        case 6:

// display text animation view from right of the screen to declared frame with out spin animation.
             [textAnimationView displayMessageViewWithPresentationType:TextAnimationViewPresentWithRightAnimation withSpinAnimation:NO];
            break;
        case 7:

// display text animation view with marquee animation from right
             [textAnimationView setTextMarquee:YES withDirectionType:TextMarqueeFromRight];
            break;
        case 8:

// display text animation view with marquee animation from left
             [textAnimationView setTextMarquee:YES withDirectionType:TextMarqueeFromLeft];
            break;
        case 9:

// display text animation view with marquee animation from Top            [textAnimationView setTextMarquee:YES withDirectionType:TextMarqueeFromTop];
            break;
        case 10:

// display text animation view with character animation(one by one character animation)
             [textAnimationView displayTextWithTypingAnimation:@"It's a sample marquee message."];
            break;
           
        default:
            break;
    }
}


Now run the project and click on buttons for display text message with animations.
Click here for download sample project.


Monday, 10 October 2016

CABasicAnimation

CABasicAnimation provides basic, single-keyframe animation capabilities for a layer property.
CABasicAnimation class animates a layer property between two values, a starting and an ending value. To move a layer from one point to another in its containing window, for example, we can create a basic animation using the keypath position. We give the animation a start value and an ending value and add the animation to the layer.

Here i am going to create a search animation, animation start with a small circle with minimum radius and continue increase the radius and after maximum radius again its start animate the circle from minimum radius.

First create  a Project(SearchActivityIndicatorViewSample)

Now create a new file(SearchActivityIndicatorView) which is subclass of UIView.
We are going to display a animated circle, so for creating a  circle i am going to declare another Class(SearchActivityIndicatorCircleView) inside "SearchActivityIndicatorView".
SearchActivityIndicatorCircleView class also a subclass of UIView.

Ok, Why i am creating a separate class for display a circle?
Answer is, if we want to display more than one circle as a search indicator so we can use multiple instance of that class and we don't need to write code for multiple circle. So by using this approach     we can avoid duplication of code.
 and also declare a property for stroke color inside "SearchActivityIndicatorCircleView Class".

here the code snippet

@interface SearchActivityIndicatorCircleView : UIView
{
   
}
@property (nonatomic, strong) UIColor *strokeColor;
@end


//Implementation 
@implementation SearchActivityIndicatorCircleView

@end


Add the following methods  inside SearchActivityIndicatorCircleView implementation.
-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame: frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


-(void) drawRect:(CGRect)rect{
    //Drawing Code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
    UIBezierPath *circlePath = [UIBezierPath bezierPath];
    [circlePath addArcWithCenter:CGPointMake(self.bounds.size.width/2, self.frame.size.height/2) radius:MIN(self.frame.size.width, self.frame.size.height)/2 - 5  startAngle:DEGREES_TO_RADIANS(0) endAngle:DEGREES_TO_RADIANS(360) clockwise:YES];
    CGPathRef cgPath = CGPathCreateCopy(circlePath.CGPath);
    CGContextAddPath(context, cgPath);
    CGContextSetLineWidth(context, 1);
    CGContextDrawPath(context, kCGPathStroke);
    CGPathRelease(cgPath);
}


In the first method i override initWithFrame: method for creating a new instance for the class.
and in the second method drawRect: i am creating a circle. Radius of circle is not static, its will depend on the frame size of View.
For calculating the radius i used smallest value between width and height and after getting smallest value reduce 5 from the that, and with the resultant value drawing circle.

Now we have enough code for draw a circle, only need to create a instance of a class and as a sub-view.

Now Switch to SearchActivityIndicatorView.h Class and add following codes.
@interface SearchActivityIndicatorView : UIView
{
    CGFloat maxScale, minScale;
}
@property (nonatomic, assign) BOOL isAnimating;
@property (nonatomic, strong) UIColor *strokeColor;
@property (nonatomic, assign) NSTimeInterval animationDuration;

-(void) startSearching;
-(void) stopSearching;


Now switch to SearchActivityIndicatorView.m and add following code
-(instancetype) init{
    self = [super init];
    if (self) {
        [self initializeDefaultValues];
    }
    return self;
}
-(instancetype) initWithFrame:(CGRect)frame{
   
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeDefaultValues];
    }
    return self;
}
-(void) awakeFromNib{
    [super awakeFromNib];
    [self initializeDefaultValues];
}
-(void) initializeDefaultValues{
    //set animation suration
    self.animationDuration = 1.9f;
    //set default stroke color
    self.strokeColor = [UIColor redColor];
    //set minimum scale
    minScale = 0.3f;
    //set maximum scale

    maxScale = 8.0f;
}


First 3 methods are used to creating new instance for the class
and the last method set default value with the time of new instance creation of class.
Inside this method, i am defining default value for animation duration, color of circle' stroke, minimum and maximum scale for circle view.

Now its time to add SearchActivityIndicatorCircleView
-(void) addCircleSearchView{
   //1. get minimum value between width and height
    CGFloat width = MIN(self.frame.size.width, self.frame.size.height)/4;

   //2. Create an instance of SearchActivityIndicatorCircleView
    SearchActivityIndicatorCircleView *circleSearchView = [[SearchActivityIndicatorCircleView alloc] initWithFrame:CGRectMake(0, 0, width, width)];
    [circleSearchView setStrokeColor:self.strokeColor];
    circleSearchView.center = self.center;
    //3.Add CABasicAnimation for scale view
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    //4. set animation duration time
    scaleAnimation.duration = self.animationDuration;
    //5. set repeat count to maximum
    scaleAnimation.repeatCount = CGFLOAT_MAX;
    //6. set minimum value for animation
    scaleAnimation.fromValue = @(minScale);
    //7. set maximum value for animation
    scaleAnimation.toValue = @(maxScale);
    //8. set timing function
    scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

    //9. add animation to Circle layer
    [circleSearchView.layer addAnimation:scaleAnimation forKey:kSearchScaleAnimationKey];
   //10. add SearchActivityIndicatorCircleView as a subview
    [self addSubview:circleSearchView];
}


Above method create an instance for  SearchActivityIndicatorCircleView, add basic animation for animate a circle and add newly created instances as a subview.
Here step by step explanations:
1. Find minimum value between width and height of frame and divide by 4 means the frame of circle view is 4 times less than SearchActivityIndicatorView.
2. Create an instance of  SearchActivityIndicatorCircleView with the minimum frame size.
3. Create an instance of CABasicAnimation with key "transform.scale".
4. set animation duration, the time require for animation of a circle from minimum scale to maximum scale.
5. set repeat count for animation.
6. set minimum scale or starting scale for animation.
7. set maximum scale for animating the circle.
8. timingFunction: A timing function defining the pacing of the animation.
    CAMediaTimingFunction represents one segment of a function describing a timing curve. The
    function maps an input time normalized to the range [0,1] to an
    output time also in the range [0,1]. E.g. these functions are used
    to define the pacing of an animation over its duration (or over the
   duration of one keyframe). Click here for more detail about CAMediaTimingFunction.

9. add animation to circle layer. CABasicAnimation provide capabilities for animate layer property, so we add animation to layer of circle view.
10. Add circle view as a subview.

We have code for draw a circle, add animation to circle.
So,  now its time to display animation, add below code in SearchActivityIndicatorCircleView.m

-(void) startSearching{
   //check if animation is already started
    if (self.isAnimating) {
        return;
    }

   //set flag value true
    self.isAnimating = YES;

  //add circle
    [self addCircleSearchView];
}


 first we are checking, is animation already started if yes than no need to start animation again.
If no than set the flag value true so we can check animation status later.
and last line send a message to  "addCircleSearchView" method for adding a circle view.




Also write a method for stop animation.
-(void) stopSearching{
    if(!self.isAnimating) {
        return;
    }
    for(UIView *searchView in self.subviews) {
        [UIView animateWithDuration:0.9f animations:^{
            searchView.transform = CGAffineTransformMakeScale(7.0f, 7.0f);
            [searchView setAlpha:0.0f];
        } completion:^(BOOL finished) {
            [searchView.layer removeAllAnimations];
            [searchView removeFromSuperview];
        }];
    }
    self.isAnimating = NO;
}


thats enough.
Now Its time for display our effort to end user.
Switch to ViewController.h class, import SearchActivityIndicatorView

add a property IBOutlet  for SearchActivityIndicatorView
@property (nonatomic, weak) IBOutlet SearchActivityIndicatorView *seachActivityIndicatorView;
and add a IBAction for handle user action.
-(IBAction)handleTapGesture:(UITapGestureRecognizer *)sender;

Now switch to  main.storyboard and drag a UIView from Object library.
Select that view and go to identity inspector and change the class from UIView to SearchActivityIndicatorView
 


Connect IBOutlet to SearchActivityIndicatorView.
Add a Tap Gesture Recognizer  to SearchActivityIndicatorView and connect IBAction method.

Now go to ViewController.m class and method for start animation
-(IBAction)handleTapGesture:(UITapGestureRecognizer *)sender{
   
    if (self.seachActivityIndicatorView.isAnimating == YES) {
        [self.seachActivityIndicatorView stopSearching];
    }
    else{
        [self.seachActivityIndicatorView startSearching];
    }
}


Run the app and tap on the screen, we can see a animated circle on screen.
Click here for complete project.

Friday, 29 April 2016

Pan Gesture Recognizer



For basic overview of Gesture Recognizer Click here
We will continue here with Pan Gesture Recognizer. Pan Gesture Recognizer allow to drag view around the screen.In this part, except for implementing the necessary code that will enable our app to support the pan gesture.
The pan gesture is actually a drag gesture. It’s used when it’s needed to drag views from one point to another.

First create a view
UIView *panView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
panView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:panView];

Defining Callback method for Gesture Recognizer

-(void) handlepanGesture:(UIPanGestureRecognizer *)panGesture{
    CGPoint touchPoint = [panGesture locationInView:self.view];
    panView.center = touchPoint;
}


Now run the app and check.
You can drag 'Pan View' around main View.

The approach I presented above is simple for the sake of the tutorial. In a real application, you might want to enrich the movement of the view by adding acceleration or deceleration when you start or stop dragging, or anything else you need. It’s up to you to apply the proper logic in the action method you implement.

You can find points per second the dragged view travels in both the horizontal and vertical axis while dragging by method velocityInView: .
Go to Callback method and add following codes

//find velocity
       CGPoint velocity = [panGesture velocityInView:self.view];
       NSLog(@"Horizontal Velocity: %.2f points/sec",velocity.x);
       NSLog(@"Vertical Velocity: %.2f points/sec",velocity.y);

Now run the app again and drag panView.
you can check horizontal  and vertical velocity on Console Area.

</script>

Friday, 22 April 2016

Swipe Gesture

In this tutorial i am going to show how to use UISwipeGestureRecognizer in the App.
You can find basic overview of Gesture Recognizer in the Previous tutorials.Click here
By using UISwipeGestureRecognizer we can swipe a view in any of the following directions:
1)  Left
2) Right
3) Top
4) Bottom

UISwipeGestureRecognizer class provide a method that allow to specify direction for swipe, if none is set, than right direction used by default.
A Swipe Gesture Recognizer object can monitor and trigger action for specified direction only.
Means, if we want a view in application that support swiping in more than one direction than need to add more than one Swipe Gesture Recognizer to view or you can change direction of Swipe Gesture Recognizer to swipe a view in different direction with one Swipe Gesture.

In this example i will use one Swipe Gesture for swiping a view in left and right both direction.

I assume you know how to create New project, i am not going to show here, mainly i will focus on how to how to use Swipe Gesture in a application.

Firstly i am creating a view.
UIView *swipeView =  [[UIView alloc] initWithFrame:self.view.bounds];
swipeView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:swipeView];


Now i am going to define Callback method for Gesture Recognizer
-(void) handleSwipeGesture:(UISwipeGestureRecognizer *)swipeGesture{
         NSLog(@"Swipe Gesture Detected");
}


Adding Gesture to view
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
[swipeView addGestureRecognizer:swipeGesture];


Its enough, if you run the app, can see a orange view above the main view. if you swipe orange view to right, Gesture Recognizer triggered and send a message to  Callback method.
for confirmation you can check and console, you can see "Swipe Gesture Detected" printed on console.
Now  i am going to swipe orange view from left to right (if orange view origin.x is 0) and from right to left(if orange view origin.x is greater than 0).
Go to 'handleSwipeGesture:' and add following code

-(void) handleSwipeGesture:(UISwipeGestureRecognizer *)swipeGesture{
         UISwipeGestureRecognizerDirection direction = swipeGesture.direction;
//give specified          Direction
         UIView *swipeView = swipeGesture.view; //return instance of specified view
         //Check Specified Direction
         if (direction==UISwipeGestureRecognizerDirectionRight) {
                [UIView animateWithDuration:.6 animations:^{
                swipeView.frame = CGRectMake(300, swipeView.frame.origin.y, swipeView.frame.size.width,    swipeView.frame.size.height);
              swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft; //Change direction
             }];
      
       }
     else if (direction==UISwipeGestureRecognizerDirectionLeft) {
            [UIView animateWithDuration:.6 animations:^{
                 swipeView.frame = CGRectMake(0, swipeView.frame.origin.y, swipeView.frame.size.width,  swipeView.frame.size.height);
                 swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //Change direction
         }];
      
    }
   else{
            NSLog(@"Unknown Direction");
   }
}



Now run app again and check.
After swipe  toward Right, Orange view slide to right, and again swipe toward Left Orange View slide left.

Note:  If you swipe toward Right Orange view slide to right and again you swipe toward right its won't work, because we changed direction from Right to Left.

Friday, 18 March 2016

View Animation

A constraint defines a relationship between two user interface objects that must be satisfied by the constraint-based layout system.

For presenting a view with constraint if little bit different.
We can use frame property for animating a view object.
We can change size and origin by setting new value inside animation block.

Here an example for animating 2 UIView object with constraint.

1) Add one UIView object on XIB file.
set following constraint
  a) Leading constraint(Margin from left)  = 0
  b)Tailing constraint(margin from right) = 0
  c) Top constraint(from super view) = 0
  d) Height constraint = 0

2) Add one more UIView object.(for differentiate set different-2 background color)
 set following constraint on newly added UIView object
  a) Leading constraint(Margin from left)  = 0
  b)Tailing constraint(margin from right) = 0
  c) Top constraint (From first UIView object not from super view)= 0
  d)Bottom constraint = 0

Now, define a IBOutlet property for NSLayoutConstraint
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topHeightConstraint;

On XIB connect topHeightConstraint with Height Constraint of Top or first UIView object.






Add a button for animating both view.
Here action of button

-(void) animationButtonAction:(UIBarButtonItem *)barButton{
    if (self.topHeightConstraint.constant == 0) {
        NSLog(@"Increase height");
        self.topHeightConstraint.constant = 300;
    }
    else{
        NSLog(@"Decrease height");
        self.topHeightConstraint.constant = 0;
    }
    [UIView animateWithDuration:1 animations:^{
        [self.view layoutIfNeeded];
    }];
}


Now, Its all set for animating UIView objects with NSLayoutConstraint.=