Ios首页投稿(暂停使用,暂停投稿)程序员

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

2016-08-10  本文已影响457人  Devil雅馨

一个简单的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.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
//
//  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
//
//  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
上一篇下一篇

猜你喜欢

热点阅读