在iOS的动画处理中,我们经常会碰到一些页面切换的效果,比如新页面代替旧的页面,为了实现某些特定的效果,我们需要把旧页面先保存下来,然后经过一定的动画处理,过渡到新的页面,这种情况下,renderInContext就派上用场了。
renderInContext可以通过把当前页面内容画到Core Graphics的context,来实现类似于截图的功能。
- (void)viewDidLoad { [super viewDidLoad]; self.button = [UIButton buttonWithType:UIButtonTypeCustom]; self.button.frame = CGRectMake(0, 0, 200, 40); self.button.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds)); [self.button setTitle:@"Perform Transition" forState:UIControlStateNormal]; [self.button setBackgroundColor:[UIColor blueColor]]; self.button.layer.cornerRadius = 5.0f; self.button.layer.masksToBounds = YES; [self.button addTarget:self action:@selector(performTransition) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.button]; } - (void)performTransition { // Preserve the current view snapshot UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0.0); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *coverImage = UIGraphicsGetImageFromCurrentImageContext(); // Insert snapshot view in front of this one UIView *coverView = [[UIImageView alloc] initWithImage:coverImage]; coverView.frame = self.view.bounds; [self.view addSubview:coverView]; // Update the view (well simply randomize the layer background color) CGFloat red = arc4random() / (CGFloat)INT_MAX; CGFloat green = arc4random() / (CGFloat)INT_MAX; CGFloat blue = arc4random() / (CGFloat)INT_MAX; self.view.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0]; // Perform animatioin [UIView animateWithDuration:1.0 animations:^{ // Scale, rotate and fade the view CGAffineTransform transform = CGAffineTransformMakeScale(0.01, 0.01); transform = CGAffineTransformRotate(transform, M_PI_2); coverView.transform = transform; coverView.alpha = 0.0; }completion:^(BOOL finished) { [coverView removeFromSuperview]; }]; }
效果就是下面的样子