指スライドアニメーション
指をスライドしてアニメーションするビューを作ります。
立体物を周囲からカメラで撮影して指のスライドで回転させたりするために使います。
普通にアニメーションの再生ポイントを指でグリグリ動かす用途にも使えます。
前準備としてアニメーションをjpgの連番等にして保存しておきます。
UIAnimationView.h
#import <UIKit/UIKit.h> @interface UIAnimationView : UIView { NSMutableArray *_imageArr; UIImageView *_imageView; int _currentFrame; int _lastFrame; } -(void)addImage:(NSString*)fname extension:(NSString*)ext; @end
UIAnimationView.m
#import "UIAnimationView.h" @implementation UIAnimationView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { _currentFrame = 0; _lastFrame = -1; _imageArr = [[NSMutableArray alloc]init]; _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; [self addSubview:_imageView]; } return self; } -(void)update { if(_lastFrame == _currentFrame)return; if([_imageArr count] == 0)return; _imageView.image = nil; _imageView.image = [_imageArr objectAtIndex:_currentFrame]; _lastFrame = _currentFrame; } -(void)addImage:(NSString *)fname extension:(NSString*)ext; { NSString *imagePath = [[NSBundle mainBundle] pathForResource:fname ofType:ext]; [_imageArr addObject:[[UIImage alloc] initWithContentsOfFile:imagePath]]; [self update]; } -(void)setFrame:(CGRect)rect { _imageView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height); super.frame = rect; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint currentPosition = [touch locationInView:self]; float pos = currentPosition.x / self.frame.size.width; if(pos<=0.0)pos = 0.0; if(pos>=1.0)pos = 1.0; _currentFrame = (int)( ([_imageArr count]-1) * pos); [self update]; } - (void)dealloc { for(int i=0; i<[_imageArr count]; i++){ UIImage *img = [_imageArr objectAtIndex:i]; [img release]; } [_imageView release]; [_imageArr release]; [super dealloc]; } @end
呼び出し
UIAnimationView *a = [[UIAnimationView alloc] initWithFrame:CGRectMake(0,0, 640,480 )]; for(int i=0; i<50; i++){ [a addImage: [NSString stringWithFormat:@"mov_%d",i] extension:@"jpg"]; } [self addSubview:a];
このサンプルではファイルを mov_0.jpg〜mov_49.jpgとしてプロジェクトフォルダに保存してあるものとします。