CABasicAnimation CGRect 扩大不工作

CABasicAnimation CGRect enlarging not working

我正在尝试使用 CABasicAnimation,以便使用自动反转使视图变大然后变小。我导入了 QuartzCore。我正在使用以下代码:

    CABasicAnimation *enlarge = [CABasicAnimation animationWithKeyPath:@"enlargeKeyPath"];
    CGRect currentSize = CGRectMake(20, 27, _moveView.bounds.size.width, _moveView.bounds.size.height);
    CGRect newSize = CGRectMake(20, 27, 45, 46);
    enlarge.fromValue = [NSValue valueWithCGRect:currentSize];
    enlarge.toValue = [NSValue valueWithCGRect:newSize];
    enlarge.autoreverses = YES;
    enlarge.repeatCount = 3.0;
    enlarge.duration = 0.5;
    [_moveView.layer addAnimation:enlarge forKey:@"enlargeKeyPath"];

但是,该代码不起作用。有人可以帮忙吗?

我觉得开头的 animationWithKeyPath 键和 forKey 和结尾的键有问题。我不知道这些是干什么用的。有人可以帮忙吗?谢谢!

而不是"enlargeKeyPath",这里我们需要的其实是transform.scale;因此,我们将动画缩放如下:

CABasicAnimation *enlarge = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
enlarge.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(3.0f, 3.0f, 1.0f)];
//To value is the value we wish your view to be scaled up (or down) to.
enlarge.autoreverses = YES;
enlarge.repeatCount = 3.0;
enlarge.duration = 0.5;
[_moveView.layer addAnimation:enlarge forKey:@"enlargeKeyPath"];

如果你真的想在框架上缩放,我们应该使用 keyPath bounds 而不是前面提到的 frame

因此,您的代码将是:

CABasicAnimation *enlarge = [CABasicAnimation animationWithKeyPath:@"bounds"];
CGRect currentSize = CGRectMake(20, 27, _moveView.bounds.size.width, _moveView.bounds.size.height);
CGRect newSize = CGRectMake(20, 27, 45, 46);
enlarge.toValue = [NSValue valueWithCGRect:newSize];
enlarge.autoreverses = YES;
enlarge.repeatCount = 3.0;
enlarge.duration = 0.5;
[_moveView.layer addAnimation:enlarge forKey:@"enlargeKeyPath"];

对于您可以使用的 keyPath 的其他值,请参阅文档 here

以下对我有用:

CABasicAnimation *enlarge = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
CGSize currentSize = _moveView.bounds.size;
CGSize newSize = CGSizeMake(_moveView.bounds.size.height * 1.5, _moveView.bounds.size.width * 1.5);
enlarge.fromValue = [NSValue valueWithCGSize:currentSize];
enlarge.toValue = [NSValue valueWithCGSize:newSize];
enlarge.autoreverses = YES;
enlarge.repeatCount = INFINITY;
enlarge.duration = 5.0;
[_moveView.layer addAnimation:enlarge forKey:@"enlargeKeyPath"];

您遇到的基本问题是混淆动画键路径(animationWithKeyPath: 的参数)和动画键(addAnimation:forKey:

的参数

animationWithKeyPath: 将要进行动画处理的视图属性的关键路径作为参数。要为视图的边界设置动画,您可以使用 "bounds",同样您可以使用 "bounds.origin" 或 "bounds.size"

addAnimation:forKey: 将一个键作为参数,它允许您在将来识别这个特定的动画。