图片的无限循环在iOS开发中非常常见,常见的实现方式有三种:使用UIScrollView,使用UICollectionView,和今天我要献丑的转场动画。
完成后的效果如图:
本程序用到了3张图片,分别命名为0,1,2.
** 第一步:声明一下图片的个数和显示图片的控件以及当前显示的图片下标。**
NSInteger const IMAGE_COUNT = 3;
@interface TransitionAnimationController ()
{
UIImageView *_imageView;
NSInteger _currentIndex;
}
第二步:初始化UI,添加手势。
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
- (void)setupUI
{
//定义图片控件
_imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
_imageView.contentMode = UIViewContentModeScaleAspectFit;
_imageView.image = [UIImage imageNamed:@"0.jpg"];
[self.view addSubview:_imageView];
//添加手势
UISwipeGestureRecognizer *leftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipe:)];
leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:leftSwipeGesture];
UISwipeGestureRecognizer *rightSwipeGesture =[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe:)];
rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:rightSwipeGesture];
}
第三步:编写手势的响应方法。
#pragma mark - 左滑
- (void)leftSwipe:(UISwipeGestureRecognizer *)gesture
{
[self transitionAnimation:YES];
}
#pragma mark - 右滑
- (void)rightSwipe:(UISwipeGestureRecognizer *)gesture
{
[self transitionAnimation:NO];
}
第四步:编写转场动画。
#pragma mark - 转场动画
- (void)transitionAnimation:(BOOL)isNext
{
//创建转场动画
CATransition *transition = [[CATransition alloc] init];
//设置动画类型
transition.type = @"push";
//设置子类型
if (isNext) {
transition.subtype = kCATransitionFromRight;
}
else
{
transition.subtype = kCATransitionFromLeft;
}
//设置动画时常
transition.duration = .8f;
//设置转场后的新视图
_imageView.image = [self getImage:isNext];
//添加转场动画
[_imageView.layer addAnimation:transition forKey:nil];
}
第五步:取得当前图片。
#pragma mark - 取得当前图片
- (UIImage *)getImage:(BOOL)isNext
{
if (isNext) {
_currentIndex = (_currentIndex + 1) % IMAGE_COUNT;
}
else
{
_currentIndex = (_currentIndex - 1 + IMAGE_COUNT) % IMAGE_COUNT;
}
NSString *imageName = [NSString stringWithFormat:@"%ld.jpg", (long)_currentIndex];
return [UIImage imageNamed:imageName];
}
在取得当前图片中用到了一个求余算法,为了方便理解我这里用Python敲了一下:
求余算法.jpg到这里就算是结束,下篇见。
网友评论