瀑布流相册+自定义跳转动画

一个简单的demo, 关于自定义瀑布流和自定义转场动画, 功能值实现了一部分,是可以反图片的真实大小的,所以我的网络加载的图片就增加了两个字段width和height,网络加载图片的问题就这么解决了吧!手势返回还没有添加(与scrollview自带的手势冲突,还没解决),只支持按钮返回. 如果有建议的话可以给我留言,最重要的一点是返回的时候会自己定位,算是这样吧! 废话不多说, 下面进入正题!

下面, 我会把代码详细写出来的, 尽量让所有人都能实现!

//
//  XZPhotoBrowserViewController.h
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/4.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface XZPhotoBrowserViewController : UIViewController

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableDictionary *offsetDictionary;

@end

//
//  XZPhotoBrowserViewController.m
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/4.
//  Copyright © 2016年 高雅馨. All rights reserved.
//


#import "XZPhotoBrowserViewController.h"
#import "XZPhotoBrowserItem.h"
#import "XZPhotoBrowserFlowLayout.h"
#import "PhotoDetailViewController.h"
#import "XZPhotoBrowserPushTransition.h"
#import "XZPhotoBrowserModel.h"
#import "UIImageView+WebCache.h"

@interface XZPhotoBrowserViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate, PhotoDetailDelegate>
/**
 *  数据源数组
 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/**
 *  存放标识符的字典(不知道重用的解决办法,有的话可以告诉我qq:916391479)
 */
@property (nonatomic, strong) NSMutableDictionary *identifierDic;
/**
 *  自定义描述对象
 */
@property (nonatomic, strong) XZPhotoBrowserFlowLayout *flowLayout;
/**
 *  存放从plist中取出的数据
 */
@property (nonatomic, strong) NSMutableArray *plistArray;

@end

static NSString *identifier = @"identifierCell";

@implementation XZPhotoBrowserViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.delegate = self;
}
/**
 *  push到详情页的时候走自定义动画
 */
- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    if ([toVC isKindOfClass:[PhotoDetailViewController class]]) {
        //初始化自定义push动画
        XZPhotoBrowserPushTransition *transition = [[XZPhotoBrowserPushTransition alloc]init];
        return transition;
    }else{
        return nil;
    }
}

- (void)xzPhotoBrowserSelectIndex:(NSInteger)index
{
    UICollectionViewLayoutAttributes *attributes = self.flowLayout.itemsAttributes[index];
    CGFloat bottomLine = attributes.frame.origin.y + attributes.frame.size.height + 5;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height - 64;
    if (bottomLine > screenH) {
        self.collectionView.contentOffset = CGPointMake(0, bottomLine - screenH);
    }else{
        self.collectionView.contentOffset = CGPointMake(0, 0);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //从plist中取出数据,转为模型,存放到数组中
    NSString *path = [[NSBundle mainBundle] pathForResource:@"photos.plist" ofType:nil];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *arr = dic[@"content"];
    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XZPhotoBrowserModel *model = [[XZPhotoBrowserModel alloc] init];
        [model setValuesForKeysWithDictionary:arr[idx]];
        [self.plistArray addObject:model];
    }];
    //初始化标识符字典
    self.identifierDic = [NSMutableDictionary dictionary];
    //将集合视图添加到view上
    [self.view addSubview:self.collectionView];
}
/**
 *  添加数据按钮
 */
- (IBAction)addAction:(UIBarButtonItem *)sender {
    if (self.dataArray.count == self.plistArray.count) return;
    [self.dataArray addObject:self.plistArray[self.dataArray.count]];
    self.flowLayout.images = self.dataArray;
    [self.collectionView reloadData];
}
/**
 *  清除所有数据按钮
 */
- (IBAction)clearAction:(UIBarButtonItem *)sender {
    //清空数据源
    [self.dataArray removeAllObjects];
    //清空标识符字典
    [self.identifierDic removeAllObjects];
    [self.offsetDictionary removeAllObjects];
    //刷新UI
    [self.collectionView reloadData];
}

#pragma mark --- 代理方法
// 设置分区内视图个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
// 设置视图cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //从标识符字典中根据key取出唯一的标识符
    NSString *fier = [self.identifierDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
    if (fier == nil) {
        //如果不存在,创建一个唯一的标识符
        fier = [NSString stringWithFormat:@"XZPhotoBrowser%@", indexPath];
        //添加到字典中
        [self.identifierDic setValue:fier forKey:[NSString stringWithFormat:@"%@", indexPath]];
        //注册item
        [self.collectionView registerClass:[XZPhotoBrowserItem class] forCellWithReuseIdentifier:fier];
    }
    //从重用池中取出item
    XZPhotoBrowserItem *cell = [collectionView dequeueReusableCellWithReuseIdentifier:fier forIndexPath:indexPath];
    XZPhotoBrowserModel *model = self.dataArray[indexPath.row];
    [cell.photo sd_setImageWithURL:[NSURL URLWithString:model.url] placeholderImage:nil];
    [self.offsetDictionary setObject:@(cell.frame.origin.y + cell.frame.size.height + 5) forKey:[NSString stringWithFormat:@"%ld", indexPath.row]];
    return cell;
}
- (NSMutableDictionary *)offsetDictionary
{
    if (!_offsetDictionary) {
        _offsetDictionary = [NSMutableDictionary dictionary];
    }
    return _offsetDictionary;
}

// 设置分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//item点击事件(push到详情)
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoDetailViewController *detail = [[PhotoDetailViewController alloc] init];
    detail.dataArray = self.dataArray;
    detail.delegate = self;
    detail.selectIndex = indexPath.row;
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark ---- 懒加载
//集合视图
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
//自定义描述对象
- (XZPhotoBrowserFlowLayout *)flowLayout
{
    if (!_flowLayout) {
        _flowLayout = [[XZPhotoBrowserFlowLayout alloc] init];
        _flowLayout.images = self.dataArray;
        _flowLayout.xzColumnsCount = 3;
    }
    return _flowLayout;
}
//数据源
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}
//plist数据
- (NSMutableArray *)plistArray
{
    if (!_plistArray) {
        _plistArray = [NSMutableArray array];
    }
    return _plistArray;
}

@end
//
//  PhotoDetailViewController.h
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/4.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol PhotoDetailDelegate <NSObject>

- (void)xzPhotoBrowserSelectIndex:(NSInteger)index;

@end

@interface PhotoDetailViewController : UIViewController

@property (nonatomic, strong) UICollectionView *collectionView;
/**
 *  数据源
 */
@property (nonatomic, copy) NSArray *dataArray;
/**
 *  当前显示的item下标
 */
@property (nonatomic, assign) NSInteger selectIndex;
/**
 *  创建一个临时的imageView,用于实现动画效果
 */
@property (nonatomic, strong) UIImageView *tmpImageView;

@property (nonatomic, assign) id<PhotoDetailDelegate> delegate;

@end
//
//  PhotoDetailViewController.m
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/4.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import "PhotoDetailViewController.h"
#import "PhotoDetailItem.h"
#import "XZPhotoBrowserViewController.h"
#import "XZPhotoBrowserPopTransition.h"
#import "XZPhotoBrowserModel.h"
#import "UIImageView+WebCache.h"
#import "PublicMethod.h"

@interface PhotoDetailViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate>

//手势没做呢!!!手势没做呢!!!手势没做呢!!!
@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *percentDrivenTransition;

@end

@implementation PhotoDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Browzer";
    self.navigationController.delegate = self;
    //注册
    [self.collectionView registerClass:[PhotoDetailItem class] forCellWithReuseIdentifier:@"identifier"];
    //将集合视图添加到view上
    [self.view addSubview:self.collectionView];
    self.view.backgroundColor = [UIColor blackColor];
    //设置集合视图偏移量
    self.collectionView.contentOffset = CGPointMake(self.view.frame.size.width * self.selectIndex, 0);
    //设置临时imageview显示的哪张图片
    [self initTmpImageView:self.selectIndex];
    self.collectionView.hidden = YES;
}

/**
 *  设置临时imageview显示的哪张图片
 */
- (void)initTmpImageView:(NSInteger)index
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(xzPhotoBrowserSelectIndex:)]) {
        [self.delegate xzPhotoBrowserSelectIndex:index];
    }
    XZPhotoBrowserModel *model = self.dataArray[index];
    [self.tmpImageView sd_setImageWithURL:[NSURL URLWithString:model.url] placeholderImage:nil];
    //定宽
    CGFloat w = self.view.frame.size.width - 10;
    //根据宽高比例获得高
    CGFloat h = [PublicMethod getImageHeight:CGSizeMake(model.width, model.height) width:w];
    //设置frame
    self.tmpImageView.frame = CGRectMake(5, (self.view.frame.size.height - 64 - h) / 2.0, w, h);
}

-(void)edgePanGesture:(UIScreenEdgePanGestureRecognizer *)recognizer
{
    CGFloat progress = [recognizer translationInView:self.view].x / (self.view.bounds.size.width * 1.0);
    progress = MIN(1.0, MAX(0.0, progress));
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.percentDrivenTransition = [[UIPercentDrivenInteractiveTransition alloc] init];
        [self.navigationController popViewControllerAnimated:YES];
    }else if (recognizer.state == UIGestureRecognizerStateChanged){
        [self.percentDrivenTransition updateInteractiveTransition:progress];
    }else if (recognizer.state == UIGestureRecognizerStateCancelled || recognizer.state == UIGestureRecognizerStateEnded){
        if (progress > 0.5) {
            [self.percentDrivenTransition finishInteractiveTransition];
        }else{
            [self.percentDrivenTransition cancelInteractiveTransition];
        }
        self.percentDrivenTransition = nil;
    }
}

- (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController
{
    if ([animationController isKindOfClass:[XZPhotoBrowserPopTransition class]]) {
        return self.percentDrivenTransition;
    }else{
        return nil;
    }
}

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    XZPhotoBrowserPopTransition *pop = [[XZPhotoBrowserPopTransition alloc] init];
    return pop;
}
/**
 *  根据活动偏移量设置临时imageview图片
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.selectIndex = scrollView.contentOffset.x / self.view.frame.size.width;
    [self initTmpImageView:self.selectIndex];
}

#pragma mark --- 代理方法
// 设置分区内视图个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
// 设置视图cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoDetailItem *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    XZPhotoBrowserModel *model = self.dataArray[indexPath.row];
    [cell.detailImageView sd_setImageWithURL:[NSURL URLWithString:model.url] placeholderImage:nil];
    return cell;
}

// 设置分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
/**
 *  点击事件
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld", (long)indexPath.row);
}
#pragma mark ---- 懒加载
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        // item尺寸
        flowLayout.itemSize = CGSizeMake(self.view.frame.size.width - 10, self.view.frame.size.height - 64);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor blackColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
    }
    return _collectionView;
}
//临时imageview
- (UIImageView *)tmpImageView
{
    if (!_tmpImageView) {
        _tmpImageView = [UIImageView new];
        [self.view addSubview:_tmpImageView];
        _tmpImageView.contentMode = UIViewContentModeScaleAspectFit;
        _tmpImageView.alpha = 0;
    }
    return _tmpImageView;
}
//数据源
- (NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = @[];
    }
    return _dataArray;
}

@end
//
//  XZPhotoBrowserFlowLayout.h
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/7/30.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import <UIKit/UIKit.h>

@class XZPhotoBrowserModel;

@interface XZPhotoBrowserFlowLayout : UICollectionViewFlowLayout

@property (nonatomic, copy) NSArray<XZPhotoBrowserModel *> *images;
/**
 *  列数 默认为2
 */
@property (nonatomic, assign) NSUInteger xzColumnsCount;

@property (nonatomic,strong)NSMutableArray *itemsAttributes;//保存所有列高度的数组

@end
//
//  XZPhotoBrowserFlowLayout.m
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/7/30.
//  Copyright © 2016年高雅馨. All rights reserved.
//

#import "XZPhotoBrowserFlowLayout.h"
#import "XZPhotoBrowserItem.h"
#import "XZPhotoBrowserModel.h"

@interface XZPhotoBrowserFlowLayout ()

@property (nonatomic,assign)NSUInteger columnsCount;
@property (nonatomic,strong)NSMutableArray *COLUMNSHEIGHTS;//保存所有列高度的数组

@end

@implementation XZPhotoBrowserFlowLayout

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (void)prepareLayout
{
    //设置列数 列数大于等于2
    self.columnsCount = self.xzColumnsCount ? self.xzColumnsCount > 2?self.xzColumnsCount:2 : 2;
    //获取item个数
    NSUInteger itemCounts = [[self collectionView] numberOfItemsInSection:0];
    //初始化
    self.itemsAttributes = [NSMutableArray arrayWithCapacity:itemCounts];
    
    self.COLUMNSHEIGHTS = [NSMutableArray arrayWithCapacity:self.columnsCount];
    for (NSInteger index = 0; index < self.columnsCount; index++) {
        [self.COLUMNSHEIGHTS addObject:@0];
    }
    
    for (NSUInteger index = 0; index < itemCounts; index++) {
        //找到最短列
        XZPhotoBrowserModel *model = self.images[index];
        NSUInteger shtIndex = [self findShortestColumn];
        
        NSUInteger origin_x = shtIndex * ([self columnWidth] + 5) + 5;
        
        NSUInteger origin_y = [self.COLUMNSHEIGHTS[shtIndex] integerValue] + 5;
        
        NSUInteger size_width = 0;
        if (shtIndex < self.columnsCount - 1 && [self.COLUMNSHEIGHTS[shtIndex] floatValue] == [self.COLUMNSHEIGHTS[shtIndex+1] floatValue] && model.width >= 1.5 * model.height) {
            size_width = 2 * [self columnWidth];
        }else{
            size_width = [self columnWidth];
        }
        NSUInteger size_height = [self getImageHeight:CGSizeMake(model.width, model.height) width:size_width];
        if (size_width == 2 * [self columnWidth]) {
            self.COLUMNSHEIGHTS[shtIndex] = @(origin_y + size_height);
            self.COLUMNSHEIGHTS[shtIndex + 1] = @(origin_y + size_height);
        }else{
            self.COLUMNSHEIGHTS[shtIndex] = @(origin_y + size_height);
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        attributes.frame = CGRectMake(origin_x, origin_y, size_width, size_height);
        [self.itemsAttributes addObject:attributes];
    }
}

- (NSUInteger)getImageHeight:(CGSize)size width:(NSUInteger)width
{
    float integerW = size.width;
    float integerH = size.height;
    float scale = width / integerW;
    NSNumber *number = [NSNumber numberWithFloat:scale * integerH];
    return [number unsignedIntegerValue];
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.itemsAttributes;
}
//设置集合视图contentsize
- (CGSize)collectionViewContentSize
{
    CGSize size = self.collectionView.bounds.size;
    NSUInteger longstIndex = [self findLongestColumn];
    float columnMax = [self.COLUMNSHEIGHTS[longstIndex] floatValue];
    size.height = columnMax + 5;
    return size;
}

#pragma mark ---- public
//找出最短列
- (NSUInteger)findShortestColumn
{
    NSUInteger shortestIndex = 0;
    CGFloat shortestValue = MAXFLOAT;
    
    NSUInteger index = 0;
    for (NSNumber *columnHeight in self.COLUMNSHEIGHTS) {
        if ([columnHeight floatValue] < shortestValue) {
            shortestValue = [columnHeight floatValue];
            shortestIndex = index;
        }
        index++;
    }
    return shortestIndex;
}
//寻找最长列
- (NSUInteger)findLongestColumn
{
    NSUInteger longestIndex = 0;
    CGFloat longestValue = 0;
    
    NSUInteger index = 0;
    for (NSNumber *columnHeight in self.COLUMNSHEIGHTS) {
        if ([columnHeight floatValue] > longestValue) {
            longestValue = [columnHeight floatValue];
            longestIndex = index;
        }
        index++;
    }
    return longestIndex;
}

- (float)columnWidth
{
    return roundf((self.collectionView.bounds.size.width - (self.columnsCount + 1) * 5) / self.columnsCount);
}

@end
  • 这里是动画所需要的代码, 只需要在XZPhotoBrowserPopTransition.h里签一个<UIViewControllerAnimatedTransitioning>协议就OK
//
//  XZPhotoBrowserPopTransition.m
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/3.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import "XZPhotoBrowserPopTransition.h"
#import "XZPhotoBrowserViewController.h"
#import "PhotoDetailViewController.h"
#import "PhotoDetailItem.h"
#import "XZPhotoBrowserItem.h"
#import "XZPhotoBrowserFlowLayout.h"

@implementation XZPhotoBrowserPopTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.7f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    PhotoDetailViewController *fromVC = (PhotoDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    XZPhotoBrowserViewController *toVC = (XZPhotoBrowserViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    UIImageView *snapShotView = [UIImageView new];
    snapShotView.image = fromVC.tmpImageView.image;
    snapShotView.backgroundColor = [UIColor redColor];
    snapShotView.frame = [containerView convertRect:fromVC.tmpImageView.frame fromView:fromVC.tmpImageView.superview];
    fromVC.collectionView.hidden = YES;
    
    
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    
    [containerView insertSubview:toVC.view belowSubview:fromVC.view];
    [containerView addSubview:snapShotView];
    
    XZPhotoBrowserFlowLayout *flowLayout = (XZPhotoBrowserFlowLayout *)toVC.collectionView.collectionViewLayout;
    UICollectionViewLayoutAttributes *attributes = flowLayout.itemsAttributes[fromVC.selectIndex];
    UIView *tmpView = [UIView new];
    //这个颜色一定要和collectionview的背景色一样
    tmpView.backgroundColor = [UIColor whiteColor];
    
    [toVC.collectionView addSubview:tmpView];
    tmpView.frame = CGRectMake(attributes.frame.origin.x, attributes.frame.origin.y, attributes.frame.size.width, attributes.frame.size.height);
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0f usingSpringWithDamping:0.6f initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        fromVC.view.alpha = 0.0f;
        snapShotView.frame = CGRectMake(attributes.frame.origin.x, attributes.frame.origin.y + 64 - toVC.collectionView.contentOffset.y, attributes.frame.size.width, attributes.frame.size.height);
    } completion:^(BOOL finished) {
        [snapShotView removeFromSuperview];
        fromVC.collectionView.hidden = NO;
        [tmpView removeFromSuperview];
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

@end
  • .h同上(⊙o⊙)哦
//
//  XZPhotoBrowserPushTransition.m
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/3.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import "XZPhotoBrowserPushTransition.h"
#import "XZPhotoBrowserViewController.h"
#import "PhotoDetailViewController.h"
#import "XZPhotoBrowserItem.h"
#import "PhotoDetailItem.h"

@implementation XZPhotoBrowserPushTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.7f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    XZPhotoBrowserViewController *fromVC = (XZPhotoBrowserViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PhotoDetailViewController *toVC = (PhotoDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    XZPhotoBrowserItem *cell = (XZPhotoBrowserItem *)[fromVC.collectionView cellForItemAtIndexPath:[[fromVC.collectionView indexPathsForSelectedItems] firstObject]];
    
    UIImageView *snapShotView = [UIImageView new];
    snapShotView.image = cell.photo.image;
    snapShotView.frame = [containerView convertRect:cell.photo.frame fromView:cell.photo.superview];
    cell.photo.hidden = YES;
    
    toVC.view.frame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.alpha = 0;
    toVC.collectionView.hidden = YES;
    
    [containerView addSubview:toVC.view];
    [containerView addSubview:snapShotView];
    
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0f usingSpringWithDamping:0.6f initialSpringVelocity:1.0f options:UIViewAnimationOptionCurveLinear animations:^{
        [containerView layoutIfNeeded];
        toVC.view.alpha = 1;
        snapShotView.frame = [containerView convertRect:CGRectMake(toVC.tmpImageView.frame.origin.x, toVC.tmpImageView.frame.origin.y, toVC.tmpImageView.frame.size.width, toVC.tmpImageView.frame.size.height) fromView:toVC.tmpImageView.superview];
    } completion:^(BOOL finished) {
        toVC.collectionView.hidden = NO;
        cell.photo.hidden = NO;
        [snapShotView removeFromSuperview];
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];
}

@end
  • 这里呢, 就是我开头所说的增加了两个字段width和height
//
//  PublicMethod.h
//  XZPhotoBrowser
//
//  Created by 高雅馨 on 16/8/6.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface PublicMethod : NSObject

/**
 *  根据宽高比例获得高
 *
 *  @param size  图片size
 *  @param width 实际宽度
 *
 *  @return 实际高度
 */
+ (CGFloat)getImageHeight:(CGSize)size width:(CGFloat)width;

@end

//
//  PublicMethod.m
//  XZPhotoBrowser
//
//  Created by高雅馨 on 16/8/6.
//  Copyright © 2016年 高雅馨. All rights reserved.
//

#import "PublicMethod.h"

@implementation PublicMethod

+ (CGFloat)getImageHeight:(CGSize)size width:(CGFloat)width
{
    float integerW = size.width;
    float integerH = size.height;
    float scale = width / integerW;
    NSNumber *number = [NSNumber numberWithFloat:scale * integerH];
    return [number floatValue];
}

@end
  • 写到这里我们就大功告成了, 还不错吧!下面就来看看我们努力的成果咯!
  • 第一次做动态图, 效果有点不清晰哦,(__) 嘻嘻……凑合看吧! 喜欢就给留个赞再走哦❤️
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,071评论 25 707
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,066评论 5 13
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,421评论 6 30
  • 感受 没有优美的语言,没有华丽的辞藻。坚持一字一句的记录生活。当是和自己交流。 有的时候,莫名的...
    爱丽丝的月牙兔阅读 164评论 0 0
  • Activity简介 Activity是一种展示型组件,用于向用户直接展示一个界面,并且可以接受用户的输入信息从而...
    蓝枫zeke阅读 1,840评论 4 9