使用UIViewAnimationOptionBeginFromCurrentState不能按预期工作的animate transform.scale

时间:2014-10-24 08:01:39

标签: ios objective-c cocoa-touch animation uikit

我想将UIView(self.square)的scale属性设置为10%:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [UIView animateWithDuration:2
                      delay:0.0
                    options: UIViewAnimationOptionBeginFromCurrentState
                 animations:^{
                     self.square.layer.affineTransform = CGAffineTransformMakeScale(0.1f, 0.1f);
                 }completion:^(BOOL finished){

                 }];
    [self performSelector:@selector(animationInterrupt) withObject:nil afterDelay:1];
}

我想在中间某处中断动画(例如:用户互动),动画比例回到100%:

- (void)animationInterrupt {
   [UIView animateWithDuration:1
                      delay:0.0
                    options: UIViewAnimationOptionBeginFromCurrentState
                 animations:^{
                     self.square.layer.affineTransform =  CGAffineTransformMakeScale(1.0f, 1.0f);
                 }completion:^(BOOL finished){

                 }];
}

这种动画的输出很奇怪。在某些时刻,它将self.square扩展到100%以上:

enter image description here

1 个答案:

答案 0 :(得分:1)

我发现以下作品

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                                      target: self
                                                    selector:@selector(transform)
                                                    userInfo: nil repeats:YES];
    [timer fire];
}    

转换函数检查动画是否已在运行并将fromvalue设置为当前值

- (void)transform {
    double toValue = 0.1;
    if (self.goingUp) toValue = 1.0;
    self.goingUp = !self.goingUp;
    CATransform3D oldTransform = [(CALayer *)[self.transforemer.layer presentationLayer] transform];
    double fromValue = oldTransform.m11;

    double duration = toValue - fromValue;
    if (fromValue > toValue) duration = fromValue - toValue;
    duration *= 2;

    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(toValue, toValue);
    self.transforemer.transform = scaleTransform;

    CABasicAnimation *shrink = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    shrink.toValue = [NSNumber numberWithDouble:toValue];
    shrink.fromValue = [NSNumber numberWithDouble:fromValue];
    shrink.duration = duration;
    shrink.fillMode=kCAFillModeForwards;
    shrink.removedOnCompletion=NO;

    [self.transforemer.layer addAnimation:shrink forKey:@"transformScale"];
}

这里看到的输出:

只需极少的努力就可以在您的情况下使用代码。