旋转始终从原始位置开始

时间:2009-10-22 11:45:32

标签: iphone core-animation

我正在尝试实现轮式功能。我计算视图的中心点,并找到在touchesMoved:方法中移动时创建的角度。对于第一步,它旋转了一定程度。但是对于下一步移动它会回到视图的原始位置然后旋转。实际上我希望从前一轮的终点开始旋转。 有什么事吗?任何帮助

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    float a, b,c;   

    UITouch *aTouch = [touches anyObject];
    if ([aTouch view] == dialView) {

        CGPoint loc = [aTouch locationInView:dialView];
        CGPoint prevloc = [aTouch previousLocationInView:dialView];

        c = [self GetSides:prevloc point2:loc]; 
        a = [self GetSides:loc point2:cntrePoint];
        b = [self GetSides:prevloc point2:cntrePoint];

        float angle = acos((a*a+b*b-c*c)/(2*a*b));// Calculating angle created on moving

        CABasicAnimation  *rotate ;
        rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        rotate.fromValue = [NSNumber numberWithFloat:0];
        rotate.toValue = [NSNumber numberWithFloat:((angle*M_PI)/180)];
        rotate.autoreverses = NO;
        rotate.fillMode = kCAFillModeForwards;
        rotate.duration = 1;
        rotate.repeatCount = 1;
        rotate.removedOnCompletion = NO;
        rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

        [dialView.layer addAnimation:rotate forKey:@"360"];
    }
}

1 个答案:

答案 0 :(得分:8)

您正在执行的动画(看起来是从this answer绘制的)同时指定了to和from值,因此每次都会从0旋转到角度弧度。这意味着您的图像将在每个动画上跳回到开头。

通常情况下,如果要删除fromValue行,则动画应该从当前角度转到新角度,但看起来转换属性的行为略有不同。您需要将fromValue设置为从图层的presentationLayer中提取的旋转变换的当前值。以下代码应从当前角度旋转到目标角度:

CABasicAnimation  *rotate;
rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotate.fromValue = [[dialView.layer presentationLayer] valueForKeyPath:@"transform.rotation.z"];
rotate.toValue = [NSNumber numberWithFloat:angle];
rotate.fillMode = kCAFillModeForwards;
rotate.duration = 1;
rotate.removedOnCompletion = NO;
rotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

请注意,我删除了toValue中的度数到弧度的转换,因为你的acos()计算以弧度为单位返回值。

EDIT(10/23/2009):纠正了我之前关于fromValue与transform属性的功能的假设。