自己动手编写一些简单的转场动画

有时候在项目开发的时候可能会有制作一些特殊的转场动画的需求,比如实现像开门一样的动画,视图从中间裂开,然后分别从两边飞出。
首先有个很实用的函数来截取当前屏幕的图片,这里的参数第一个一般填写self.view,第二个参数可以根据实际需要来写frame

-(UIImage*)captureView:(UIView *)theView frame:(CGRect)fra{
    UIGraphicsBeginImageContext(theView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef ref = CGImageCreateWithImageInRect(img.CGImage, fra);
    UIImage *i = [UIImage imageWithCGImage:ref];
    CGImageRelease(ref);
    return i;
}

这样就获取了整个屏幕的截屏图片,然后就可以设置动画可以实现左右开门或者上下打开飞出去,
-(void)pushViewController:(UIViewController *)nextViewController{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;

UIImage *redayShowVC = [self imageWithView:nextViewController.view];
UIImageView *redayShowView = [[UIImageView alloc] init];
redayShowView.image = redayShowVC;
redayShowView.hidden = YES;

// redayShowView.frame = CGRectMake(0 , 0, kScreenWidth, kScreenHeight);
redayShowView.frame = CGRectMake(self.view.center.x , self.view.center.y, 1, 1);
[self.view addSubview:redayShowView];

//先截取当前屏幕的图片
UIImage *currenScreenImage = [self captureView:appDelegate.window frame:CGRectMake(0, 0, kScreenWidth, kScreenHeight / 2)];
UIImageView *topHalf = [[UIImageView alloc] init];
topHalf.image = currenScreenImage;
topHalf.clipsToBounds = YES;
//截取屏幕下半部分的图片
UIImage *currenScreenImageBottom = [self captureView:appDelegate.window frame:CGRectMake(0, kScreenHeight / 2, kScreenWidth, kScreenHeight / 2)];
UIImageView *bottomHalf = [[UIImageView alloc] init];
bottomHalf.image = currenScreenImageBottom;
bottomHalf.clipsToBounds = YES;

[self.view addSubview:topHalf];
[self.view  addSubview:bottomHalf];


topHalf.frame = CGRectMake(0, 0,kScreenWidth, kScreenHeight / 2);
bottomHalf.frame = CGRectMake(0,kScreenHeight / 2, kScreenWidth, kScreenHeight / 2);
//实现动画
[UIView animateWithDuration:1.0 animations:^{
    topHalf.frame = CGRectMake(0, - kScreenHeight / 2, kScreenWidth, kScreenHeight / 2);
    bottomHalf.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight / 2);
    redayShowView.hidden = NO;
    //这句是缩放函数 可以注释掉
    redayShowView.transform = CGAffineTransformMakeScale(kScreenWidth, kScreenHeight);

} completion:^(BOOL finished) {
    [redayShowView removeFromSuperview];
    [topHalf removeFromSuperview];
    [bottomHalf removeFromSuperview];
    [self.navigationController pushViewController:nextViewController animated:NO];
}];

}

这样一个效果就出来了

你可能感兴趣的:(自己动手编写一些简单的转场动画)