我目前正在尝试使用核心动画和图层构建条形图视图。为了让它更酷,我试着让每根光束一个接一个地弹出一点。为方便起见,我垂直翻转了视图的坐标系。
这是代码:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.transform = CGAffineTransformMakeScale(1, -1);
self.values = @[@12.5f, @4.25f, @23.0f, @3.0f, @17.9f, @7.0f, @15.1f];
}
return self;
}
- (void)didMoveToSuperview
{
self.backgroundColor = [UIColor whiteColor];
self.beamContainer = [CALayer layer];
CGRect frame = CGRectInset(self.bounds, 20, 20);
self.beamContainer.frame = frame;
self.beamContainer.backgroundColor = [UIColor colorWithWhite:0.98 alpha:1].CGColor;
float maxValue = [[self.values valueForKeyPath:@"@max.floatValue"] floatValue];
for (int i = 0; i < self.values.count; i++) {
CALayer *beam = [CALayer layer];
CGFloat beamHeight = ([self.values[i] floatValue] * frame.size.height) / maxValue;
beam.backgroundColor = [UIColor colorWithRed:0.5 green:0.6 blue:1 alpha:1].CGColor;
beam.anchorPoint = CGPointMake(0, 0);
beam.position = CGPointMake(frame.size.width * ((float)i/(float)self.values.count), 0);
CGRect endBounds = CGRectMake(0, 0, frame.size.width /(float)self.values.count, beamHeight);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
animation.fromValue = [NSValue valueWithCGRect:CGRectMake(0, 0, frame.size.width /(float)self.values.count, 5)];
animation.toValue = [NSValue valueWithCGRect:endBounds];
animation.duration = .5;
animation.beginTime = CACurrentMediaTime() + ((float)i * 0.1);
[beam addAnimation:animation forKey:@"beamAnimation"];
[self.beamContainer addSublayer:beam];
beam.bounds = endBounds;
}
[self.layer addSublayer:self.beamContainer];
}
这就像一个魅力,唯一的问题是,如果我不写,动画完成beam.bounds = endBounds;
后光束会恢复到原来的边界。但是当我这样做时,它甚至会在动画开始之前和每个动画的延迟期间使用。endBounds
如何为从边界 A 到 B 并最终粘到 B 的光束设置动画?