покадровая анимация с UIGestureRecognizer

Я хотел бы показать анимацию с изображением вращающегося объекта. У меня есть NSArray с кадрами объекта, и я хотел бы отображать их кадр за кадром со свойством UIImageView animationImages.

Проблема в том, что я хотел бы управлять анимацией с помощью UISwipeGestureRecognizer (справа и слева). И в зависимости от скорости жеста объект должен вращаться быстрее или медленнее. Я думаю, что это невозможно, потому что жест вызывается только один раз, а не постоянно.

(ПРИМЕЧАНИЕ: это мой первый вопрос в StackOverflow)

заранее спасибо

РЕДАКТИРОВАТЬ: я просто публикую свое решение. Может кому пригодится. Я думаю, это полезно.

Во-первых: добавьте жесты в представление.

self.recognizer = [[UISwipeGestureRecognizer alloc] init];
self.recognizer.cancelsTouchesInView=NO;
[self.view addGestureRecognizer:self.recognizer];

Во-вторых: в методе tocuhMoved я отображаю нужный мне кадр в зависимости от направления предыдущего касания. Вызывается событием пользователя.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{


    NSInteger image= [self.animationView.animationImages indexOfObject:self.animationView.image];
    UITouch *touch = [touches anyObject];
    NSLog(@"Touch moved with index:%i", image);

    if ((positionTouch.x<[touch locationInView:self.animationView].x)) {
        if (image==24) {
            self.animationView.image=[self.animationView.animationImages objectAtIndex:0];
        }
        else{
            self.animationView.image=[self.animationView.animationImages objectAtIndex:image+1];
        }
    }
    else if((positionTouch.x>[touch locationInView:self.animationView].x)){
        if (image==0) {
            self.animationView.image=[self.animationView.animationImages objectAtIndex:24];
        }
        else{
            self.animationView.image=[self.animationView.animationImages objectAtIndex:image-1];
        }

    }


    positionTouch= [touch locationInView:self.animationView];
}

Не забывайте <UIGestureRecognizerDelegate>

с помощью этого метода я заполняю массив кадров...

-(void)addPictures{
    NSMutableArray* mArray=[[NSMutableArray alloc]initWithCapacity:25];
    for (int i=0; i<25; i++) {
        [mArray insertObject:[UIImage imageNamed:[NSString stringWithFormat:@"Picture %i.jpg", i+1]] atIndex:i];
    }

    self.animationView.image=[mArray objectAtIndex:0];
    self.animationView.animationImages=mArray;


    [self.view addSubview:self.animationView];

}

person TomCobo    schedule 16.04.2013    source источник


Ответы (1)


На самом деле очень просто контролировать скорость анимации. На самом деле это настолько просто (поскольку CALayer соответствует протоколу CAMediaTiming), что свойство для управления им буквально называется скорость. Все дело в использовании жеста как своего рода аналога ползунка и вычислении значения x относительно его местоположения на экране. Это должно быть подходящей отправной точкой:

//Speed changes necessitate a change in time offset, begin time, and
//speed itself.  Simply assigning to speed it not enough, as the layer needs
//to be informed that it's animation timing function is being mutated.  By
//assigning a new time offset and a new begin time, the layer 
//automatically adjusts the time of any animations being run against it
layer.timeOffset = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
layer.beginTime = CACurrentMediaTime();
layer.speed = ([self.gesture locationInView:self.view].x / CGRectGetWidth(self.view.bounds));
person CodaFi    schedule 16.04.2013