一年春好處,不在濃芳,小艷疏香,最嬌軟<不良蛙>
動(dòng)畫(huà)切換圖片的效果
動(dòng)畫(huà)切換圖片的效果
上面是效果圖:
- 代碼實(shí)現(xiàn)部分:
定義兩個(gè)屬性
# 定義一個(gè)放照片的 UIImageView
@property (strong, nonatomic) UIImageView *OurImages;
# 記錄當(dāng)前展示的照片次序 (可以理解你正在展示的是第幾張照片 從0 開(kāi)始)
@property (assign, nonatomic) NSInteger currentIndex;
思路:
目的: 實(shí)現(xiàn)滑動(dòng)切換照片
解決思路: 首先需要展示照片的 UIImageView -----> 其次要有展示的圖片(我這是五張) -----> 通過(guò)左滑右滑切換展示的圖片 -----> 同時(shí)要有動(dòng)畫(huà)效果
上代碼:
# 創(chuàng)建 UIImageView
self.OurImages = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.view addSubview:self.OurImages];
// 圖片會(huì)在 View 中顯示 并且比例不變
self.OurImages.contentMode = UIViewContentModeScaleAspectFill;
# 設(shè)置默認(rèn)的照片 和 默認(rèn)的次序 (這里要對(duì)應(yīng) 第一張圖片 對(duì)應(yīng)下標(biāo)(次序) 0)
self.OurImages.image = [UIImage imageNamed:@"001 (1).jpg"];
self.currentIndex = 0;
# 創(chuàng)建 并 添加兩個(gè)手勢(shì) 左滑右滑
# 注意: 這個(gè)手勢(shì) 默認(rèn)屬性direction(方向)只有向右滑動(dòng) 所以要為左滑動(dòng)更改下屬性 向右是默認(rèn) 可以不改
UISwipeGestureRecognizer *left = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftAction:)];
left.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:left];
UISwipeGestureRecognizer *right = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightAction:)];
[self.view addGestureRecognizer:right];
```
```code
# 左滑觸及的方法 目的是 上一張照片 給自己定義的方法傳參數(shù)標(biāo)記1
- (void)leftAction:(UISwipeGestureRecognizer *)sender
{
[self transitionAnimation:1];
}
# 右滑觸及的方法 目的是 下一張照片 給自己定義的方法傳參數(shù)標(biāo)記0
- (void)rightAction:(UISwipeGestureRecognizer *)sender
{
[self transitionAnimation:0];
}
上面是主題思路完成 下面就是完成細(xì)節(jié)的切換 實(shí)現(xiàn)滑動(dòng)觸及的方法細(xì)節(jié)
# 根據(jù)傳入的參數(shù) 切換不同的照片
- (void)transitionAnimation:(BOOL)isNext
{
// 創(chuàng)建轉(zhuǎn)場(chǎng)動(dòng)畫(huà)
CATransition *trans = [[CATransition alloc] init];
// 效果 支持的字段參考 上一篇?jiǎng)赢?huà)的總結(jié)
trans.type = @"cube";
if (isNext)
{
trans.subtype = kCATransitionFromRight;
}else
{
trans.subtype = kCATransitionFromLeft;
}
// 動(dòng)畫(huà)持續(xù)時(shí)間
trans.duration = 1.0f;
// 調(diào)用得到照片的方法
self.OurImages.image = [self getImage:isNext];
[self.OurImages.layer addAnimation:trans forKey:@"切換照片"];
}
- (UIImage *)getImage:(BOOL)isNext
{
if (isNext)
{
// 當(dāng) currentIndex = 1時(shí)候 (1+1)%5 = 2; 下一張
self.currentIndex = (self.currentIndex +1)%5;
}else
{
// 當(dāng) currentIndex = 1時(shí)候 (1-1+5)%5 = 0; 上一張
self.currentIndex = (self.currentIndex - 1 + 5)%5;
}
// 往數(shù)組里面添加圖片 圖片名與下標(biāo)名對(duì)應(yīng)
NSString *imageName = [NSString stringWithFormat:@"001 (%ld).jpg",self.currentIndex + 1];
return [UIImage imageNamed:imageName];
}