@interface ViewController () { UIView *animationView; UIButton *button; CGPoint animationPoint; } @end
初始化button和動畫的view
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; // 創建Button button = [UIButton buttonWithType:UIButtonTypeSystem]; button.layer.borderWidth = 0.5f; button.layer.cornerRadius = 7.0f; button.frame = CGRectMake(240, 50, 60, 25); [button setTitle:@"動畫" forState:UIControlStateNormal]; [button addTarget:self action:@selector(showAnimation) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; // 動畫縮放開始的點 animationPoint = CGPointMake(button.frame.origin.x + button.frame.size.width / 2, 0); // 動畫view animationView = [[UIView alloc] initWithFrame:CGRectMake(20, button.frame.origin.y + button.frame.size.height + 10, 280, 100)]; animationView.backgroundColor = [UIColor grayColor]; animationView.layer.cornerRadius = 7.0f; animationView.alpha = 0.0f; [self.view addSubview:animationView]; }
動畫的處理方法
- (void)showAnimation { CGFloat offsetX = animationPoint.x - self.view.frame.size.width / 2; CGFloat offsetY = animationPoint.y - animationView.frame.size.height / 2; if (animationView.alpha == 0.0f) { // 動畫由小變大 animationView.transform = CGAffineTransformMake(0.01, 0, 0, 0.01, offsetX, offsetY); [UIView animateWithDuration:0.3f animations:^{ animationView.alpha = 1.0f; animationView.transform = CGAffineTransformMake(1.05f, 0, 0, 1.0f, 0, 0); } completion:^(BOOL finished) { [UIView animateWithDuration:0.1f animations:^{ animationView.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0); } completion:^(BOOL finished) { // 恢復原位 animationView.transform = CGAffineTransformIdentity; }]; }]; } else { // 動畫由大變小 animationView.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0); [UIView animateWithDuration:0.2 animations:^{ animationView.transform = CGAffineTransformMake(0.01, 0, 0, 0.01, offsetX, offsetY); } completion:^(BOOL finished) { animationView.transform = CGAffineTransformIdentity; animationView.alpha = 0.0f; }]; } }
動畫效果圖