iOS 模仿系统的抖动动画

裴良弼
2023-12-01

模仿系统的抖动动画,主要用的是CAKeyframeAnimation(见之前篇博文)和NSTimer,不多说直接上代码。


#define degreesToRadians(x) (M_PI*(x)/180.0)

//左右摇摆的角度
#define RADIUS 3.0f

#define ShakeTime 0.5

//动画实现
-(void)ShakeAnimationWithView:(id)sender
{
    CAKeyframeAnimation *keyAn = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
    [keyAn setDuration:ShakeTime];
    NSArray *array = [[NSArray alloc] initWithObjects:
                      [NSNumber numberWithFloat:degreesToRadians(0.0f)],
                      [NSNumber numberWithFloat:degreesToRadians(-RADIUS)],
                      [NSNumber numberWithFloat:degreesToRadians(0.0f)],
                      [NSNumber numberWithFloat:degreesToRadians(RADIUS)],
                      [NSNumber numberWithFloat:degreesToRadians(0.0f)],
                      nil];
    [keyAn setValues:array];
    [array release] ,array = nil;
    
    NSTimer *timer = (NSTimer *)sender;
    UIView *shakeView = [viewDic objectForKey:timer.userInfo];
    
    //判断如果是UIIimageView,要进行去除锯齿效果
    if ([shakeView isKindOfClass:[UIImageView class]]) {
        shakeView = [self clearSawtoothOfView:(UIImageView *)shakeView];
    }
    [shakeView.layer addAnimation:keyAn forKey:@"shake"];
    
}

//调用该方法,开始抖动动画
-(void)startShakeWithView:(UIView *)shakeView withViewName:(NSString *)nameOfView
{
    [viewDic setObject:shakeView forKey:nameOfView];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:ShakeTime target:self selector:@selector(ShakeAnimationWithView:) userInfo:nameOfView repeats:YES];
    [timer fire];
    [timerArray addObject:timer];
}

//结束所有动画
-(void)stopShakeAll
{
    for (int i = 0; i < [timerArray count]; i++) {
        NSTimer *timer = (NSTimer *)[timerArray objectAtIndex:i];
        [timer invalidate];
        timer = nil;
    }
    [timerArray removeAllObjects];
}

//去除UIImageView的锯齿
-(UIImageView *)clearSawtoothOfView:(UIImageView *)imgView
{
    UIGraphicsBeginImageContextWithOptions(imgView.frame.size, NO, 1);
    [imgView.image drawInRect:CGRectMake(0, 0, imgView.frame.size.width, imgView.frame.size.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    [imgView setImage:image];
    return imgView;
}




 类似资料: