相簿類 App 裡「點一下照片就放大到全螢幕」的過場動畫,是使用者最有感的細節之一。自己實作需要處理 frame 插值與 dismiss 動畫,但其實有現成的第三方庫可用。本文示範以 Vertigo 搭配自訂的 transitioningDelegate 完成這個效果。
初始畫面:

點擊後:

專案結構:

#import <UIKit/UIKit.h>
@interface RootViewController : UIViewController <UIViewControllerTransitioningDelegate>
{
UIImageView *imageView;
}
@end
#import "RootViewController.h"
#import "TGRImageViewController.h"
#import "TGRImageZoomAnimationController.h"
- (void)viewDidLoad {
[super viewDidLoad];
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 200, 200)];
imageView.image = [UIImage imageNamed:@"1.jpg"];
[self.view addSubview:imageView];
// 在圖片上疊一顆透明按鈕接收點擊
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 100, 200, 200)];
btn.backgroundColor = [UIColor clearColor];
[btn addTarget:self action:@selector(doClickButton:) forControlEvents:UIControlEventTouchUpInside];
btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:btn];
}
- (void)doClickButton:(UIButton *)btn {
TGRImageViewController *viewController =
[[TGRImageViewController alloc] initWithImage:imageView.image];
viewController.transitioningDelegate = self; // 關鍵:交給自訂的動畫控制器
[self presentViewController:viewController animated:NO completion:nil];
}
presentViewController:animated: 傳的是 NO,因為動畫已由 TGRImageZoomAnimationController 自行驅動,交給系統反而會重複。userInteractionEnabled 為 NO,用按鈕是最省事的做法;若想更精簡,改用 UITapGestureRecognizer 並記得把 imageView 的 userInteractionEnabled 設為 YES 即可。UIViewControllerAnimatedTransitioning,核心就是取來源 imageView 的 frame 作為動畫起點。