旋转滚轮时在CABasicAnimation中更改CALayer的速度会导致混蛋效果

问题描述 投票:5回答:2

我开发了一个应用程序,它需要一个轮子围绕z轴旋转,随着时间的推移稳定地增加或减少轮子的速度。我用CABasicAnimation&我的代码如下。当我以特定间隔改变图层的速度属性时,它会对轮子产生“混蛋”效果。

/****/

CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.toValue = [NSNumber numberWithFloat:-2*M_PI];
animation.duration = 4.0f;
animation.repeatCount = INFINITY;
[animation setValue:@"left" forKey:@"side"];
[animation setDelegate:self];
animation.removedOnCompletion=NO;
animation.fillMode = kCAFillModeForwards;
animation.cumulative = YES;

imageLeft.layer.beginTime = CACurrentMediaTime();
/************/

在计时器中,我改变了imageview的CALayer的速度,如下所示,其中dPlayedPercentage是一个变量。

imageLeft.layer.speed=1.0+dPlayedPercentage;

[imageLeft.layer addAnimation:animation forKey:@"SpinAnimation"];

我认为这是由于在更改CALayer的速度属性时位置重置。我该怎么做才能纠正这个问题。或者其他任何方式来做这个动画?

ios objective-c performance calayer cabasicanimation
2个回答
11
投票

添加以下代码已经纠正了动画中的混蛋。

imageLeft.layer.timeOffset = [imageLeft.layer convertTime:CACurrentMediaTime() fromLayer:nil]; 
imageLeft.layer.beginTime = CACurrentMediaTime(); 
imageLeft.layer.speed=1.0+dPlayedPercentage;

0
投票

对于更加动态的速度变化,我在上一个答案中遇到了一些问题(层根本没有绘制),因为需要以新的速度计算timeOffset

(来源https://coveller.com/2016/05/core_animation_timing

timeOffset的基本公式是: timeOffset = CACurrentMediaTime() - ((convertTime - beginTime) x speed)

在代码中:

theLayer.speed = newSpeed

let mediaTime = CACurrentMediaTime()

let converedTime = theLayer.convertTime(mediaTime, to: nil)

theLayer.beginTime = mediaTime

let offset = mediaTime - ((converedTime - theLayer.beginTime) * Double(newSpeed))

theLayer.timeOffset = offset
© www.soinside.com 2019 - 2024. All rights reserved.