Very custom UIButton animation in iOS

2019-03-22 07:11发布

问题:

I have a custom button which is my own subclass of UIButton. It looks like a circled arrow, starting at some angle startAngle end finishing at some endAngle=startAngle+1.5*M_PI. startAngle is a button's property which is then used in its drawRect: method. I want to make this arrow to continuously rotate by 2Pi around its center when this button is pressed. So I thought that I can easily use [UIView beginAnimations: context:] but apparently it can't be used as it doesn't allow to animate custom properties. CoreAnimation also doesn't suite as it only animates the CALayer properties.

So what is the easiest way to implement an animation of a custom property of UIView subclass in iOS? Or maybe I missed something and it is possible with already mentioned techniques?

Thank you.

回答1:

Thanks to Jenox I have updated animation code using CADisplayLink which seems to be really more correct solution than NSTimer. So I show the correct implementation with CADisplayLink now. It is very close to the previous one, but even a bit simpler.

We add the QuartzCore framework to our project. Then we put the following lines in the header file of our class:

CADisplayLink* timer;
Float32 animationDuration;  // Duration of one animation loop
Float32 initAngle;  // Represents the initial angle 
Float32 angle;  // Angle used for drawing
CFTimeInterval startFrame;  // Timestamp of the animation start

-(void)startAnimation;  // Method to start the animation
-(void)animate;  // Method for updating the property or stopping the animation

Now in implementation file we set the values for duration of the animation and the other initial values:

initAngle=0.75*M_PI;
angle=initAngle;
animationDuration=1.5f;  // Arrow makes full 360° in 1.5 seconds
startFrame=0;  // The animation hasn't been played yet

To start the animation we need to create the CADisplayLink instance which will call method animate and add it to main RunLoop of our application:

-(void)startAnimation
{
   timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(animate)];
   [timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

This timer will call animate method every runLoop of the application.

So now comes the implementation of our method for updating the property after each loop:

-(void)animate
{
   if(startFrame==0) {
      startFrame=timer.timestamp;  // Setting timestamp of start of animation to current moment
      return;  // Exiting till the next run loop
   } 
   CFTimeInterval elapsedTime = timer.timestamp-startFrame;  // Time that has elapsed from start of animation
   Float32 timeProgress = elapsedTime/animationDuration;  // Determine the fraction of full animation which should be shown
   Float32 animProgress = timingFunction(timeProgress); // The current progress of animation
   angle=initAngle+animProgress*2.f*M_PI;  // Setting angle to new value with added rotation corresponding to current animation progress
   if (timeProgress>=1.f) 
   {  // Stopping animation
      angle=initAngle; // Setting angle to initial value to exclude rounding effects
      [timer invalidate];  // Stopping the timer
      startFrame=0;  // Resetting time of start of animation
   }
   [self setNeedsDisplay];  // Redrawing with updated angle value
}

So unlike case with NSTimer we now don't need to calculate the time interval at which to update the angle property and redraw the button. We now only need to count how much time has passed from the start of animation and set the property to value which corresponds to this progress.

And I must admit that animation works a bit more smoothly than in case of NSTimer. By default, CADisplayLink calls the animate method each run loop. When I calculated the frame rate, it was 120 fps. I think that it is not very efficient so I have decreased the frame rate to just 22 fps by changing the frameInterval property of CADisplayLink before adding it to mainRunLoop:

timer.frameInterval=3;

It means that it will call the animate method at first run loop, then do nothing next 3 loops, and call on the 4-th, and so on. That's why frameInterval can be only integer.



回答2:

Thanks again to k06a for suggestion to use timer. I've made some study about working with NSTimer and now I want to show my implementation, since I think, it can be useful for others.

So in my case I had a UIButton subclass which was drawing a curved arrow which started from some angle Float32 angle; which is the main property from which the drawing of whole arrow starts. That means that just changing the value of angle will rotate whole arrow. So to make animation of this rotation I put the following lines in the header file of my class:

NSTimer* timer;
Float32 animationDuration;  // Duration of one animation loop
Float32 animationFrameRate;  // Frames per second
Float32 initAngle;  // Represents the initial angle 
Float32 angle;  // Angle used for drawing
UInt8 nFrames;  // Number of played frames

-(void)startAnimation;  // Method to start the animation
-(void)animate:(NSTimer*) timer;  // Method for drawing one animation step and stopping the animation

Now in implementation file I set the values for duration and frame rate of my animation and the initial angles for drawing:

initAngle=0.75*M_PI;
angle=initAngle;
animationDuration=1.5f;  // Arrow makes full 360° in 1.5 seconds
animationFrameRate=15.f;  // Frame rate will be 15 frames per second
nFrames=0;  // The animation hasn't been played yet

To start the animation we need to create the NSTimer instance which will call method animate:(NSTimer*) timer every 1/15 seconds:

-(void)startAnimation
{
   timer = [NSTimer scheduledTimerWithTimeInterval:1.f/animationFrameRate target:self selector:@selector(animate:) userInfo:nil repeats:YES];
}

This timer will call animate: method immediately and then repeat it every 1/15 second until it will be manually stopped.

So now comes the implementation of our method for animating a single step:

-(void)animate:(NSTimer *)timer
{
   nFrames++;  // Incrementing number of played frames
   Float32 animProgress = nFrames/(animationDuration*animationFrameRate); // The current progress of animation
   angle=initAngle+animProgress*2.f*M_PI;  // Setting angle to new value with added rotation corresponding to current animation progress
   if (animProgress>=1.f) 
   {  // Stopping animation when progress is >= 1
      angle=initAngle; // Setting angle to initial value to exclude rounding effects
      [timer invalidate];  // Stopping the timer
      nFrames=0;  // Resetting counter of played frames for being able to play animation again
   }
   [self setNeedsDisplay];  // Redrawing with updated angle value
}

The first thing I want to mention is that for me just comparison line angle==initAngle didn't work due to rounding effects. They don't are exactly the same after full rotation. That's why I check if they are just close enough and then set angle value to initial value to block small drift of angle value after many repeated animation loops. And to be totally correct, this code must also manage conversion of angles to always be between 0 and 2*M_PI with something like this:

angle=normalizedAngle(initAngle+animProgress*2.f*M_PI);

where

Float32 normalizedAngle(Float32 angle)
{
   while(angle>2.f*M_PI) angle-=2.f*M_PI;
   while(angle<0.f) angle+=2.f*M_PI;
   return angle
}

And another important thing is that, unfortunately, I don't know any easy way to apply easeIn, easeOut or other default animationCurves to this kind of manual animation. I think it doesn't exist. But it is, of course, possible to do it by hands. The line standing for that timing function is

Float32 animProgress = nFrames/(animationDuration*animationFrameRate);

It can be treated as Float32 y = x;, that means linear behavior, a constant speed, which is the same as speed of time. But you can modify it to be like y = cos(x) or y = sqrt(x) or y = pow(x,3.f) which will give some nonlinear behavior. You can think it yourself taking into account that x will go from 0 (start of animation) to 1 (end of animation).

For better looking code it is better to make some independent timing function:

Float32 animationCurve(Float32 x)
{
  return sin(x*0.5*M_PI);
}

But now, since the dependence between animation progress and time is not linear, it's safer to use the time as indicator for stopping the animation. (You might want for example to make your arrow to make 1.5 full turns and than rotate back to the initial angle, that means your animProgress will go from 0 to 1.5 and than back to 1 while timeProgress will go from 0 to 1.) So to be safe we separate time progress and animation progress now:

Float32 timeProgress = nFrames/(animationDuration*animationFrameRate);
Float32 animProgress = animationCurve(timeProgress);

and then check time progress to decide if should the animation stop:

if(timeProgress>=1.f)
{
   // Stop the animation
}

By the way, if somebody knows some sources with list of useful timing functions for animation, I would appreciate if you share them.

Built in MacOS X utility Grapher helps a lot in visualizing the functions, so that you can see how your animation progress will depend on time progress.

Hope it helps somebody...



回答3:

- (void)onImageAction:(id)sender
{
    UIButton *iconButton = (UIButton *)sender;
    if(isExpand)
{
    isExpand = FALSE;

    // With Concurrent Block Programming:
    [UIView animateWithDuration:0.4 animations:^{
        [iconButton setFrame:[[btnFrameList objectAtIndex:iconButton.tag] CGRectValue]];
    } completion: ^(BOOL finished) {
        [self animationDidStop:@"Expand" finished:YES context:nil];
    }];
}
else
{
    isExpand = TRUE;

    [UIView animateWithDuration:0.4 animations:^{
        [iconButton setFrame:CGRectMake(30,02, 225, 205)];
    }];

    for(UIButton *button in [viewThumb subviews])
    {
        [button setUserInteractionEnabled:FALSE];
        //[button setHidden:TRUE];
    }
    [viewThumb bringSubviewToFront:iconButton];

    [iconButton setUserInteractionEnabled:TRUE];
   // [iconButton setHidden:FALSE];
    }
}