由於我們的項目需要,我正在寫一個播放序列幀的程序,第一時間想起來的就是apple中UIImageView的屬性animationImages,將一系列幀添加到一個數組里面,然后設置animation一系列屬性,如動畫時間,動畫重復次數,還是看代碼吧,直觀
imagesArray = [NSArray arrayWithObjects:
[UIImage imageNamed:@"image1.png"],
[UIImage imageNamed:@"image2.png"],
[UIImage imageNamed:@"image3.png"],
[UIImage imageNamed:@"image4.png"],
[UIImage imageNamed:@"image5.png"],nil];
animationImageView = [UIImageView alloc];
[animationImageView initWithFrame:CGRectMake(0, 0, 131, 125)];
animationImageView.animationImages = imagesArray;//將序列幀數組賦給UIImageView的animationImages屬性
animationImageView.animationDuration = 0.25;//設置動畫時間
animationImageView.animationRepeatCount = 0;//設置動畫次數 0 表示無限
[animationImageView startAnimating];//開始播放動畫
[self addSubview:animationImageView];
設置動畫的代碼結構就是這樣,如果圖片少的話也許這種方式是最快速最容易達到目的的,那么你會問圖片很多不行嗎?,恩,根據目前我做的實驗,圖片很多的話這種方式程序必須會蹦,隨后我會提到我們現在的實現方式,而且動畫不能夠實現暫停,只有停止,項目中要求序列幀播放的時候當手輕觸(touch)播放暫停,松開后繼續播放 ,橫掃(swipe)播放加速,這一系列的需求表明了用animationImages這種方式實現已經不太現實.
之后我們考慮了自己去實現UIImageView的animation效果,題目之所以說他不給力,因為UIImageView的animation不會邊用邊釋放(當然這點僅是我自己的拙見),那就導致了如果圖片很多,animation直接崩掉根本用不了,我們實現的原理就是用NSTimer去實現apple的UIImageView animation的效果,其實apple應該也是用NSTimer去實現吧(猜的),用NSTimer每隔一個時間戳去設置一次image,代碼如下
下面是自定義類去實現類似UIImageView animation代碼結構
//
// SXAnimationImageView.h
// MyAnimation
//
// Created by on 12-2-12.
// Copyright (c) 2012年 CocoaChina. All rights reserved.
//
#import <UIKit/UIKit.h>
#define LEFT -1
#define RIGHT 1
typedef enum {
SXAnimationImageViewStatePlaying,
SXAnimationImageViewStateStop,
SXAnimationImageViewStateStoped,
// add State
}SXAnimationImageViewState;
typedef enum {
SXAnimationImageViewPre,
SXAnimationImageViewNext,
}SXAnimationImageViewPreOrNext;
@interface SXAnimationImageView : UIView
{
UIImageView * _imageView;
NSTimer * _timer;
NSUInteger _currentIndex;
NSUInteger _jump;
SXAnimationImageViewPreOrNext _preOrNext;
UIPanGestureRecognizer * _panGesture;
// add Gesture
}
@property NSTimeInterval animationDuration;
@property NSUInteger animationRepeatCount;
@property NSUInteger toIndex;
@property (strong,nonatomic) NSMutableArray * animationImages;
- (void)animationTo:(NSUInteger)index_;
- (void)setCurrentImage;
- (void)startAnimating;
- (void)stopAnimating;
- (BOOL)isAnimating;
@end
實現文件部分代碼:
@interface SXAnimationImageView (SX)
- (void)preCache;// prepare read image
- (void)animationFrom:(NSUInteger)fromIndex_ To:(NSUInteger)toIndex_;
- (void)waitForStop:(NSNotification *)notification;
- (void)stateChanged:(NSNotification *)notification;
@end
@implementation SXAnimationImageView
@synthesize animationDuration = _animationDuration;
@synthesize animationRepeatCount = _animationRepeatCount;
@synthesize toIndex = _toIndex;
@synthesize animationImages = _animationImages;
@end