18

我有一个删除项目的用户界面,我想模仿 iOS 邮件中的“移动到文件夹”效果。小字母图标被“扔”到文件夹中的效果。我的会被扔进垃圾箱。

我尝试CAAnimation在图层上使用 a 来实现它。据我在文档中可以阅读,我应该能够设置 abyValue和 atoValue并且 CAAnimation 应该插入这些值。我正在寻找一条小曲线,因此该项目通过项目开始位置上方和左侧的一点。

    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setDuration:2.0f];
[animation setRemovedOnCompletion:NO];
[animation setFillMode:kCAFillModeForwards];    
[animation setTimingFunction:[CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseOut]];
[animation setFromValue:[NSValue valueWithCGPoint:fromPoint]];
[animation setByValue:[NSValue valueWithCGPoint:byPoint]];
[animation setToValue:[NSValue valueWithCGPoint:CGPointMake(512.0f, 800.0f)]];
[animation setRepeatCount:1.0];

我玩了一段时间,但在我看来苹果意味着线性插值。添加 byValue 不会计算出漂亮的弧线或曲线并通过它为项目设置动画。

我将如何去做这样的动画?

感谢您提供的任何帮助。

4

5 回答 5

32

使用 UIBezierPath

import QuartzCore(如果您使用的是 iOS 6 或更低版本,请不要忘记链接然后)

示例代码

您可以使用将遵循路径的动画,非常方便,CAKeyframeAnimation支持 a CGPath,可以从UIBezierPath. 斯威夫特 3

func animate(view : UIView, fromPoint start : CGPoint, toPoint end: CGPoint)
{
    // The animation
    let animation = CAKeyframeAnimation(keyPath: "position")

    // Animation's path
    let path = UIBezierPath()

    // Move the "cursor" to the start
    path.move(to: start)

    // Calculate the control points
    let c1 = CGPoint(x: start.x + 64, y: start.y)
    let c2 = CGPoint(x: end.x,        y: end.y - 128)

    // Draw a curve towards the end, using control points
    path.addCurve(to: end, controlPoint1: c1, controlPoint2: c2)

    // Use this path as the animation's path (casted to CGPath)
    animation.path = path.cgPath;

    // The other animations properties
    animation.fillMode              = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    animation.duration              = 1.0
    animation.timingFunction        = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseIn)

    // Apply it
    view.layer.add(animation, forKey:"trash")
}

了解 UIBezierPath

贝塞尔路径(准确地说是贝塞尔曲线)的工作方式与您在 Photoshop、烟花、草图中找到的完全一样……它们有两个“控制点”,每个顶点一个。比如我刚刚制作的动画:

在此处输入图像描述

像这样工作贝塞尔路径。请参阅有关细节的文档,但基本上是两个点将弧线“拉”向某个方向。

绘制路径

关于 的一个很酷的功能UIBezierPath是,您可以使用 将它们绘制在屏幕上CAShapeLayer,从而帮助您可视化它将遵循的路径。

// Drawing the path
let *layer          = CAShapeLayer()
layer.path          = path.cgPath
layer.strokeColor   = UIColor.black.cgColor
layer.lineWidth     = 1.0
layer.fillColor     = nil

self.view.layer.addSublayer(layer)

改进原始示例

计算自己的贝塞尔路径的想法是,您可以制作完全动态的,因此,动画可以根据多种因素改变它要做的曲线,而不是像我在示例中所做的那样仅仅硬编码,例如,控制点可以计算如下:

// Calculate the control points
let factor : CGFloat = 0.5

let deltaX : CGFloat = end.x - start.x
let deltaY : CGFloat = end.y - start.y

let c1 = CGPoint(x: start.x + deltaX * factor, y: start.y)
let c2 = CGPoint(x: end.x                    , y: end.y - deltaY * factor)

最后一点代码使得这些点与上一个图一样,但数量可变,相对于点形成的三角形,乘以一个相当于“张力”值的因子。

于 2013-07-11T08:31:38.530 回答
8

用 a 为位置设置动画是绝对正确的,因为CABasicAnimation它会沿直线移动。还有另一个类要求CAKeyframeAnimation做更高级的动画。

一个数组values

而不是toValue,fromValuebyValue对于基本动画,您可以使用数组values或完整path来确定沿途的值。如果您想先将位置动画到一边然后向下,您可以传递一个包含 3 个位置(开始、中间、结束)的数组。

CGPoint startPoint = myView.layer.position;
CGPoint endPoint   = CGPointMake(512.0f, 800.0f); // or any point
CGPoint midPoint   = CGPointMake(endPoint.x, startPoint.y);

CAKeyframeAnimation *move = [CAKeyframeAnimation animationWithKeyPath:@"position"];
move.values = @[[NSValue valueWithCGPoint:startPoint],
                [NSValue valueWithCGPoint:midPoint],
                [NSValue valueWithCGPoint:endPoint]];
move.duration = 2.0f;

myView.layer.position = endPoint; // instead of removeOnCompletion
[myView.layer addAnimation:move forKey:@"move the view"];

如果这样做,您会注意到视图从起点沿直线移动到中点,然后沿另一条直线移动到终点。通过中点从头到尾的弧线缺少的部分是更改calculationMode动画的。

move.calculationMode = kCAAnimationCubic;

您可以通过更改tensionValues,continuityValuesbiasValues属性来控制它。如果您想要更好的控制,您可以定义自己的路径而不是values数组。

Apath跟随

您可以创建任何路径并指定属性应遵循该路径。在这里我使用一个简单的弧

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL,
                  startPoint.x, startPoint.y);
CGPathAddCurveToPoint(path, NULL,
                      controlPoint1.x, controlPoint1.y,
                      controlPoint2.x, controlPoint2.y,
                      endPoint.x, endPoint.y);

CAKeyframeAnimation *move = [CAKeyframeAnimation animationWithKeyPath:@"position"];
move.path = path;
move.duration = 2.0f;

myView.layer.position = endPoint; // instead of removeOnCompletion
[myView.layer addAnimation:move forKey:@"move the view"];
于 2013-07-11T08:36:27.350 回答
4

试试这个它肯定会解决你的问题,我在我的项目中使用过这个:

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 126, 320, 24)] autorelease];
label.text = @"Animate image into trash button";
label.textAlignment = UITextAlignmentCenter;
[label sizeToFit];
[scrollView addSubview:label];

UIImageView *icon = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"carmodel.png"]] autorelease];
icon.center = CGPointMake(290, 150);
icon.tag = ButtonActionsBehaviorTypeAnimateTrash;
[scrollView addSubview:icon];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.center = CGPointMake(40, 200);
button.tag = ButtonActionsBehaviorTypeAnimateTrash;
[button setTitle:@"Delete Icon" forState:UIControlStateNormal];
[button sizeToFit];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:button];
[scrollView bringSubviewToFront:icon];

- (void)buttonClicked:(id)sender {
    UIView *senderView = (UIView*)sender;
    if (![senderView isKindOfClass:[UIView class]])
        return;

    switch (senderView.tag) {
        case ButtonActionsBehaviorTypeExpand: {
            CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
            anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            anim.duration = 0.125;
            anim.repeatCount = 1;
            anim.autoreverses = YES;
            anim.removedOnCompletion = YES;
            anim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)];
            [senderView.layer addAnimation:anim forKey:nil];

            break;
        }

        case ButtonActionsBehaviorTypeAnimateTrash: {
            UIView *icon = nil;
            for (UIView *theview in senderView.superview.subviews) {
                if (theview.tag != ButtonActionsBehaviorTypeAnimateTrash)
                    continue;
                if ([theview isKindOfClass:[UIImageView class]]) {
                    icon = theview;
                    break;
                }
            }

            if (!icon)
                return;

            UIBezierPath *movePath = [UIBezierPath bezierPath];
            [movePath moveToPoint:icon.center];
            [movePath addQuadCurveToPoint:senderView.center
                             controlPoint:CGPointMake(senderView.center.x, icon.center.y)];

            CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
            moveAnim.path = movePath.CGPath;
            moveAnim.removedOnCompletion = YES;

            CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:@"transform"];
            scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
            scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
            scaleAnim.removedOnCompletion = YES;

            CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:@"alpha"];
            opacityAnim.fromValue = [NSNumber numberWithFloat:1.0];
            opacityAnim.toValue = [NSNumber numberWithFloat:0.1];
            opacityAnim.removedOnCompletion = YES;

            CAAnimationGroup *animGroup = [CAAnimationGroup animation];
            animGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim, opacityAnim, nil];
            animGroup.duration = 0.5;
            [icon.layer addAnimation:animGroup forKey:nil];

            break;
        }
    }
}
于 2013-07-11T07:57:42.133 回答
1

我发现了如何做到这一点。真的可以分别为 X 和 Y 设置动画。如果您在同一时间(以下 2.0 秒)为它们设置动画并设置不同的计时功能,它将使它看起来像从开始到结束值以弧线而不是直线移动。要调整弧线,您需要设置不同的计时功能。但是不确定 CAAnimation 是否支持任何“性感”的计时功能。

        const CFTimeInterval DURATION = 2.0f;
        CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
        [animation setDuration:DURATION];
        [animation setRemovedOnCompletion:NO];
        [animation setFillMode:kCAFillModeForwards];    
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
        [animation setFromValue:[NSNumber numberWithDouble:400.0]];
        [animation setToValue:[NSNumber numberWithDouble:0.0]];
        [animation setRepeatCount:1.0];
        [animation setDelegate:self];
        [myview.layer addAnimation:animation forKey:@"animatePositionY"];

        animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
        [animation setDuration:DURATION];
        [animation setRemovedOnCompletion:NO];
        [animation setFillMode:kCAFillModeForwards];    
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
        [animation setFromValue:[NSNumber numberWithDouble:300.0]];
        [animation setToValue:[NSNumber numberWithDouble:0.0]];
        [animation setRepeatCount:1.0];
        [animation setDelegate:self];
        [myview.layer addAnimation:animation forKey:@"animatePositionX"];

编辑:

应该可以通过使用https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/CAMediaTimingFunction_class/Introduction/Introduction.html更改计时功能(由 functionWithControlPoints:::: 发起的 CAMediaTimingFunction)这是一个“三次贝塞尔曲线”。我确信谷歌在那里有答案。http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves :-)

于 2012-02-13T14:57:53.230 回答
0

几天前我有一个类似的问题,正如布拉德所说,我用计时器实现了它,但不是NSTimerCADisplayLink- 这是应该用于此目的的计时器,因为它与应用程序的 frameRate 同步并提供更流畅和更自然的动画。您可以在我的回答中查看我的实现。这种技术确实比 对动画提供了更多的控制CAAnimation,而且并不复杂。 CAAnimation无法绘制任何东西,因为它甚至不会重绘视图。它只会移动、变形和淡化已经绘制的内容。

于 2012-04-16T13:32:58.480 回答