UIView shake animation

后端 未结 16 1302
梦毁少年i
梦毁少年i 2020-11-28 18:07

i\'m trying to make a UIView shake when a button is pressed.

I am adapting the code I found on http://www.cimgf.com/2008/02/27/core-animation-tutorial-window-shake-e

16条回答
  •  鱼传尺愫
    2020-11-28 18:43

    Here's one that uses a damper function to decay the shake:

    - (void)shake
    {
        CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        animation.duration = 0.5;
        animation.delegate = self;
        animation.fillMode = kCAFillModeForwards;
        animation.removedOnCompletion = YES;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    
        NSMutableArray* values = [[NSMutableArray alloc] init];
    
        int steps = 100;
        double position = 0;
        float e = 2.71;
    
        for (int t = 0; t < steps; t++)
        {
            position = 10 * pow(e, -0.022 * t) * sin(0.12 * t);
            NSValue* value = [NSValue valueWithCGPoint:CGPointMake([self center].x - position, [self center].y)];
            DDLogInfo(@"Value: %@", value);
            [values addObject:value];
        }
    
        animation.values = values;
        [[self layer] addAnimation:animation forKey:@"position"];
    
    }
    

提交回复
热议问题