Switching CABasicAnimation on the position property mid animation causes a flicker

瘦欲@ 提交于 2019-12-03 10:14:50

问题


I have some code that uses CALayers to have bubbles flowing bottom to top. If the user touches the screen I have some code that replaces the currently running animation with one that has a toPoint where the finger touched down. When the animation switches it causes a flicker on the device (not on the simulator). Any tips on eliminating the flicker would be appreciated! Thanks.

Code for the bubbles flowing up inside the layer itself:

CABasicAnimation *animation = [CABasicAnimationanimationWithKeyPath:@"position"];
[animation setDelegate:self];
CGPoint position = [self position];
NSValue *prevVal = [NSValue valueWithCGPoint:position];
[animation setFromValue:prevVal];
CGPoint toPoint = CGPointMake(position.x,-100);
[animation setToValue:[NSValue valueWithCGPoint:toPoint]];
[animation setDuration:animationDuration];
[self addAnimation:animation forKey:@"flow"];

The code for attracting nearby bubbles to the touch point written in the super layer:

int count = [self.layer.sublayers count];
for(int i = 0; i < count ; i++) {
   CALayer *layer= [self.layer.sublayers objectAtIndex:i];
   CALayer *p = (CALayer*)[layer presentationLayer];
   CGPoint position = [p position];

   if(abs(position.x - touchPoint.x) < 100 && abs(position.y - touchPoint.y) < 100) {

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setDelegate:self];
    NSValue *prevVal = [NSValue valueWithCGPoint:position];
    [animation setFromValue:prevVal];
    [animation setToValue:[NSValue valueWithCGPoint:touchPoint]];
    [animation setDuration:2.0];
    [animation setTimingFunction:[CAMediaTimingFunction  
            functionWithName:kCAMediaTimingFunctionEaseOut]];
    [layer addAnimation:animation forKey:@"flow"];
   }        

}


回答1:


Try using a CATransaction lock around your updates to see if that helps. This will prevent the previous animations from changing the position of the layers while you're in the process of updating them with new animations.

In your touch handling method, wrap the animations in a transaction and lock:

[CATransaction lock];
[CATransaction begin];

// update the sublayers with new animations

[CATransaction commit];
[CATransaction unlock];


来源:https://stackoverflow.com/questions/1102896/switching-cabasicanimation-on-the-position-property-mid-animation-causes-a-flick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!