gpt4 book ai didi

iphone : remove CALayer when animation stop, CALayer 消失前闪烁

转载 作者:行者123 更新时间:2023-12-03 18:28:35 28 4
gpt4 key购买 nike

  • 在 XCode 中创建一个简单的项目
  • 设置 View 以接收多点触控事件
  • 在touchesBegan中响应,检测到触摸事件时创建CALayer
  • 为 CALayer 制作不透明度淡出动画
  • 当动画停止时,从父级中删除 CALayer

预期:CALayer正常消失

实际:CALayer在消失前闪烁

完整源代码:

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.view.multipleTouchEnabled = YES;
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch* touch in touches) {
CGPoint p = [touch locationInView:self.view];

//NSLog(@"touch=%@ p=%@", touch, NSStringFromCGPoint(p));

CALayer *layer = [CALayer layer];
layer.position = p;
layer.bounds = CGRectMake(0, 0, 70, 70);
layer.cornerRadius = 30;
layer.masksToBounds = NO;
layer.backgroundColor = [UIColor colorWithRed:102.0/255.0 green:156.0/255.0 blue:255.0/255.0 alpha:0.8].CGColor;
layer.shouldRasterize = YES;

CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeOutAnimation.fromValue = [NSNumber numberWithFloat:1.0];
fadeOutAnimation.toValue = [NSNumber numberWithFloat:0.0];
fadeOutAnimation.duration = 0.5;
fadeOutAnimation.delegate = self;
fadeOutAnimation.removedOnCompletion = NO;
[fadeOutAnimation setValue:layer forKey:@"parentLayer"];
[layer addAnimation:fadeOutAnimation forKey:@"opacity"];

[self.view.layer addSublayer:layer];
}
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
if(flag) {
CALayer *layer = [theAnimation valueForKey:@"parentLayer"];
if(layer) {
layer.opaque = NO;
layer.opacity = 0.0;
//layer.hidden = YES;
//NSLog(@"The layer object was: %@ (%@)", layer, [layer name]);
[layer removeFromSuperlayer];
[layer removeAllAnimations];
}
}
}

@end

最佳答案

tl;dr: 将动画上的 fillMode 设置为 kCAFillModeForwards 或在将动画添加到之前将值更改为其最终值层。

<小时/>

基本动画只是动画期间的视觉动画,不改变实际值。当您将动画设置为在完成后不删除时,这意味着该图层仍将引用动画对象作为其动画之一。然而它已经运行了它的动画。

动画外观(填充模式)的默认行为是kCAFillModeRemoved,这意味着在动画持续时间结束后,图层看起来就像动画从未发生过一样。通过将填充模式更改为 kCAFillModeForwardskCAFillModeBoth,您可以使图层看起来好像图层仍处于动画的最终状态。

您可以使用 kCAFillModeBackwards 在动画开始时执行相同的操作,但它主要适用于您设置动画开始时间的情况。

因此,要使动画看起来像动画的最终状态一样,您可以将填充模式设置为 ...Forwards 并且不删除动画或更改动画的实际值在将动画添加到 View 之前,将图层设置为您期望的值。这将更改值,然后从旧值动画到新值。

关于iphone : remove CALayer when animation stop, CALayer 消失前闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10602505/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com