使用UICollectionView实现3D效果的轮播

在很多APP上都看到过带有3D效果的广告轮播,当时觉得很酷炫。后来我就尝试去写代码实现类似的效果,实现起来其实也比较简单,首先看下运行后的效果:


效果

下面主要分享下主要的实现过程

首先创建自定义的UICollectionView

#import <UIKit/UIKit.h>

@interface AbbrCollectionView : UICollectionView

@property (nonatomic, strong) NSArray *images;

@end

images存储要轮播显示的图片(demo里是本地的图片,正常情况应该都是网络请求的图片)

#import "AbbrCollectionView.h"
#import "AbbrLayoutView.h"

@interface AbbrCollectionView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) AbbrLayoutView *layout;

@end

@implementation AbbrCollectionView

- (instancetype)initWithFrame:(CGRect)frame {
    _layout = [[AbbrLayoutView alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    _layout.itemSize = CGSizeMake(frame.size.width / 2, frame.size.height - 10);
    if (self = [super initWithFrame:frame collectionViewLayout:_layout]) {
        self.backgroundColor = [UIColor orangeColor];
        self.showsHorizontalScrollIndicator = NO;
        self.contentInset = UIEdgeInsetsMake(0, (int)(frame.size.width / 4) + 5, 0, (int)(frame.size.width / 4) + 5);
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    }
    return self;
}

- (void)setImages:(NSArray *)images {
    _images = images;
    [self scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_images.count / 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}
#import "ViewController.h"
#import "AbbrCollectionView.h"

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) AbbrCollectionView *collectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    _datas = [NSMutableArray array];
    for (int i = 1; i < 10; i ++) {
        [_datas addObject:[NSString stringWithFormat:@"timg%d.jpg",i]];
    }
    _collectionView = [[AbbrCollectionView alloc] initWithFrame:CGRectMake(0, screenH / 4, screenW, screenH / 2)];
    _collectionView.images = _datas;
    [self.view addSubview:_collectionView];
}

@end

因为是3D的旋转效果,原生的UICollectionViewFlowLayout布局并不能满足要求,这里需要自定义一个AbbrLayoutView的布局。初始化的时候根据需要设置Layout的itemSize及sectionInset等属性。在设置图片数据源images时,让CollectionView滚动至中间位置。
然后实现UICollectionView代理及数据源

- (void)setImages:(NSArray *)images {
    _images = images;
    [self scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_images.count / 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    UIImage *image = [UIImage imageNamed:_images[indexPath.row]];
    cell.backgroundView = [[UIImageView alloc] initWithImage:image];
    cell.layer.cornerRadius = 10;
    cell.layer.masksToBounds = YES;
    return cell;
}

这里cell只是显示图片,并没有其他控件,所以直接使用UICollectionViewCell没有自定义。
屏幕显示的不止当前一张图片,不能直接使用系统的pagingEnabled属性设置分页效果,所以接下来还需实现UIScrollView的代理自己控制分页的效果:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat scrDynameter = scrollView.contentOffset.x / (_layout.itemSize.width + 10);
    if(!decelerate){
        NSInteger scrIndex = (NSInteger)(scrDynameter + 1);
        [self scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:scrIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat scrDynameter = scrollView.contentOffset.x / (_layout.itemSize.width + 10);
    NSInteger scrIndex = (NSInteger)(scrDynameter + 1);
    [self scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:scrIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

自定义UICollectionViewFlowLayout

#import "AbbrLayoutView.h"

@implementation AbbrLayoutView

///  返回collectionView上面当前显示的所有元素(比如cell)的布局属性:这个方法决定了cell怎么排布
///  每个cell都有自己对应的布局属性:UICollectionViewLayoutAttributes
///  要求返回的数组中装着UICollectionViewLayoutAttributes对象
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    CGRect visitRect = {self.collectionView.contentOffset,self.collectionView.bounds.size};
// 需要copy原来的attributes 否则会有警告:This is likely occurring because the flow layout subclass xxxx is modifying attributes returned by UICollectionViewFlowLayout without copying them
    NSMutableArray *attributesCopy = [NSMutableArray array];
    for (UICollectionViewLayoutAttributes *attribute in attributes) {
        UICollectionViewLayoutAttributes *attributeCopy = [attribute copy];
        [attributesCopy addObject:attributeCopy];
    }
    
    for (UICollectionViewLayoutAttributes *attribute in attributesCopy) {
        CGFloat distance = CGRectGetMidX(visitRect) - attribute.center.x;
        CGFloat coefficient = distance / (self.itemSize.width * 6); // 根据每个cell的距离设置旋转系数
        attribute.transform3D = CATransform3DMakeRotation(coefficient * M_PI , 1, 0, 0); // 旋转
    }
    return attributesCopy;
}

// 当边界发生改变时,是否应该刷新布局。如果YES则在边界变化(一般是scroll到其他地方)时,将重新计算需要的布局信息。
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

@end

自定义UICollectionViewFlowLayout需要重写- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect方法,旋转效果都写在这个方法里,通过NSArray<UICollectionViewLayoutAttributes *>数组返回。

到这里似乎已大功告成了,很开心的运行代码,但发现结果并不是我们想要的:

22.jpg

明明设置的是CATransform3DMakeRotation旋转效果,为什么运行的结果是缩放的效果呢?
这是因为,在CALayer的显示系统中,默认的相机使用正交投影,正交投影没有远小近大效果,所以在本例中,只能造成相应轴上的缩放。所以需要通过矩阵连乘自己构造透视投影矩阵,代码如下:

/* center:相机的位置,相机的位置是相对于要进行变换的CALayer的来说的,
原点是CALayer的anchorPoint在整个CALayer的位置,
例如CALayer的大小是(100, 200), anchorPoint值为(0.5, 0.5),
此时anchorPoint在整个CALayer中的位置就是(50, 100),正中心的位置。
传入透视变换的相机位置为(0, 0),那么相机所在的位置相对于CALayer就是(50, 100)。
如果希望相机在左上角,则需要传入(-50, -100)。disZ:相机离z=0平面(也可以理解为屏幕)的距离*/
CATransform3D CATransform3DMakePerspective(CGPoint center, float disZ) {
    CATransform3D transToCenter = CATransform3DMakeTranslation(-center.x, -center.y, 0);
    CATransform3D transBack = CATransform3DMakeTranslation(center.x, center.y, 0);
    CATransform3D scale = CATransform3DIdentity;
    scale.m34 = -1.0f / disZ;
    return CATransform3DConcat(CATransform3DConcat(transToCenter, scale), transBack);
}

CATransform3D CATransform3DPerspect(CATransform3D t, CGPoint center, float disZ) {
    return CATransform3DConcat(t, CATransform3DMakePerspective(center, disZ));
}

有关这部分内容可以参考这篇博客

最后把刚才attribute.transform3D = CATransform3DMakeRotation(coefficient * M_PI , 1, 0, 0);的代码换成透视投影就能实现3D的效果:

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    CGRect visitRect = {self.collectionView.contentOffset,self.collectionView.bounds.size};
    NSMutableArray *attributesCopy = [NSMutableArray array];
    for (UICollectionViewLayoutAttributes *attribute in attributes) {
        UICollectionViewLayoutAttributes *attributeCopy = [attribute copy];
        [attributesCopy addObject:attributeCopy];
    }
    
    for (UICollectionViewLayoutAttributes *attribute in attributesCopy) {
        CGFloat distance = CGRectGetMidX(visitRect) - attribute.center.x;
        CGFloat coefficient = distance / (self.itemSize.width * 6);
        //        attribute.transform3D = CATransform3DMakeRotation(coefficient * M_PI , 1, 0, 0);
        CATransform3D rotate = CATransform3DMakeRotation(coefficient * M_PI, 0, 1, 0);
        attribute.transform3D = CATransform3DPerspect(rotate, CGPointMake(0, 0), 200);
    }
    return attributesCopy;
}

demo

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

推荐阅读更多精彩内容

  • Sass&Gulp 一、sass介绍 (一) SASS是一种CSS的开发工具,提供了许多便利的写法,大大节省了设计...
    锋享前端阅读 1,501评论 0 3
  • 小课堂对于自执行函数的理解: 什么是自执行函数? 网上对这种类型的函数的叫法众说纷纭。 ...
    OK_8242阅读 882评论 0 1
  • 跑步,越来越受到当下活在城市中的人们喜爱,国内外各大赛事此起彼伏,各种商业活动页层出不穷。跑步所带来身体的改变,传...
    Joe_Lee_Run阅读 185评论 0 0
  • 人与自然之间的近,有时候是在那一瞬间体会到的。 冬天的黄海森林公园就是这样,它突然就走进了我的心...
    杨沐云舒阅读 1,593评论 13 18
  • 扔掉你心里在读的诗 它既忧郁又狂热 因为你不懂 认为我歇斯底里 ---写于2016年。
    卡布奇诺花蜜阅读 990评论 2 50