iOS 用Swipe手势和动画实现循环播放图片示例

2020-01-18 21:05:40于海丽

向左轻扫,middleImage显示上一张图片,则图片的下标index是当前展示图片的下标 - 1。而为了实现无限循环并不超出数组的下标范围,则需要加上图片的张数之后在%图片的张数。


/**
 向左轻扫响应方法
 */
- (void)circleSwipeImageToLeft {
UIImage *currentImage = self.middleImage.image;
NSInteger index = [self.imageArray indexOfObject:currentImage];
index = (index - 1 + self.imageArray.count) % self.imageArray.count;

[self changeAnimation:index toRight:NO];
}

最后是对middleImage.layer添加动画。


#pragma mark - 添加动画

/**
 为middleImage添加动画效果

 @param index  图片数组下标
 @param toRight 是否是向右滑动
 */
- (void)changeAnimation:(NSInteger)index toRight:(BOOL)toRight {
CATransition *transition = [CATransition animation];
transition.type = kCATransitionReveal; //设置动画过渡的方式

if (toRight) {
  //向右滑动,则图片是由左向右运动
  transition.subtype = kCATransitionFromLeft;
}
else {
  //向左滑动,则图片是由右向左运动
  transition.subtype = kCATransitionFromRight;
}

//将动画添加middleIamge.layer上
[self.middleImage.layer addAnimation:transition forKey:nil];

NSInteger count = self.imageArray.count;

if (index >= 0 && index < count) {
  //更改middleImage展示的图片
  self.middleImage.image = self.imageArray[index];
}
}

还有,图片可以选中了之后直接拉到项目的Assets.xcassets里面

ios,循环播放图片,ios图片循环滚动,swipe手势

最终效果如下:

ios,循环播放图片,ios图片循环滚动,swipe手势

其实在这个项目中,leftImage和rightImage都没有显示图片,可以去掉,为了展示有多张图片的效果,可以在middleImage后面添加一个加了边框的UIView。

而在这个项目中,有一个局限,就是transition.type 只能指定是kCATransitionReveal格式,其他的格式的过渡效果都比较差。可以使leftImage和rightImage展示图片,然后将位置调整一下,并且修改transition.type看一下效果。下面是更改为kCATransitionPush的效果。

ios,循环播放图片,ios图片循环滚动,swipe手势

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到IOS开发频道。