Search code examples
objective-cioscore-animation

Shrinking a frame 80% without explicitly defining the CGRect


I'm trying to animate a button. The button will start with a height and width of 0 and expand to 100% of its intended size. It will then shrink down to 80% its size and then back up to 100% again.

Is there a way to do this without having to explicitly calculate the CGRect for each position? The problem is that when at 80% the frame is not perfectly aligned with the position of the frame at 100%. I have to manually calculate the x and y position of the frame which is time consuming since I'm doing this for a lot of buttons.

Here is what i'm currently trying to do:

    CGRect smallPlay = CGRectMake(PlayButton.frame.origin.x + 94, PlayButton.frame.origin.y + 23, 0, 0);
    CGRect almostFullPlay = CGRectMake(40, 170, 160, 30);

    [UIView animateWithDuration:0.3
                    delay:0
                    options: UIViewAnimationCurveEaseOut
                    animations:^{

                     PlayButton.frame = smallPlay;
                     PlayButton.frame = CGRectMake(50, 178, 187, 45);

                 } 
                 completion:^(BOOL finished){
                     [UIView animateWithDuration:0.2 
                         delay:0 
                         options:UIViewAnimationCurveEaseOut 
                         animations:^{

                             PlayButton.frame = almostFullPlay;
                             PlayButton.frame = CGRectMake(50, 178,187, 45);

                     } completion:^(BOOL finished){
                         NSLog(@"Done!");
                     }
                      ];
                 }];

Edit: I realize that I could write a function to calculate the frame at 80% but I was wondering if there is a better way to do this that would not require me to write anything extra.


Solution

  • Looks like you just want to temporarily manipulate the button's appearance. If that's the case, instead of transforming its frame, try transforming its transform! Here's a starting point. Let me know if you need a bit more to understand.

    [UIView
        animateWithDuration:  ...
        delay:                ...
        options:              UIViewAnimationCurveEaseOut
        animations:           ^ {
            PlayButton.transform = CGAffineTransformMakeScale(0.8, 0.8);
        }];
    

    To restore the button to its original transformation (called the "identity transform"), set its transform property to CGAffineTransformIdentity.

    Once you've got that figured out, read up on CGAffineTransform (the Quartz cousin of NSAffineTransform, and the 2D great uncle of CATransform3D.)