- 在 XCode 中创建一个简单的项目
- 设置视图以接收多点触控事件
- 在 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