iOS 为视图添加抖动效果

时间:2023-03-08 23:57:22
iOS 为视图添加抖动效果

抖动效果在开发中比较少用到,不过有时使用了确有个很好的装逼效果,用的时候就例如一些用户错误操作之类的

效果如下,不过gif看到的效果没实际的好看

iOS 为视图添加抖动效果

上代码

 - (void)shakeAnimationForView:(UIView *) view

 {
// 获取到当前的View CALayer *viewLayer = view.layer; // 获取当前View的位置 CGPoint position = viewLayer.position; // 移动的两个终点位置 CGPoint x = CGPointMake(position.x + , position.y); CGPoint y = CGPointMake(position.x - , position.y); // 设置动画 CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; // 设置运动形式 [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]]; // 设置开始位置 [animation setFromValue:[NSValue valueWithCGPoint:x]]; // 设置结束位置 [animation setToValue:[NSValue valueWithCGPoint:y]]; // 设置自动反转 [animation setAutoreverses:YES]; // 设置时间 [animation setDuration:.]; // 设置次数 [animation setRepeatCount:]; // 添加上动画 [viewLayer addAnimation:animation forKey:nil]; }

只要在需要的地方传进视图就可以了

例如:

     view1 = [[UIView alloc]initWithFrame:CGRectMake(, , , )];
view1.backgroundColor = [UIColor blueColor];
view1.layer.cornerRadius = ;
[self.view addSubview:view1]; } - (IBAction)beginView:(id)sender {
[self shakeAnimationForView:view1];
}