2013-07-17 68 views
1

我目前正在嘗試使用Core Animation和圖層來創建條形圖視圖。 爲了讓它變得更涼爽,我試圖讓每束光芒一個接一個地彈出來。 爲了方便起見,我垂直翻轉了視圖的座標系。Core Animation:正確設置動畫屬性

下面的代碼:

- (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上end

+0

看看CATransaction(http://developer.apple.com/library/ios/ipad/#documentation/GraphicsImaging/Reference/CATransaction_class/Introduction/Introduction.html),也許它會更好地滿足您的需求。另外,看到這個職位:http://oleb.net/blog/2012/11/prevent-caanimation-snap-back/ – architectpianist

+0

你使用自動佈局? – rdelmar

回答

0

你可以嘗試像以下:

// Save the original value 
CGFloat originalY = layer.position.y; 

// Change the model value (this is not animated yet) 
layer.position = CGPointMake(layer.position.x, 300.0); 

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"]; 

// Now specify the fromValue for the animation because 
// the current model value is already the correct toValue 
animation.fromValue = @(originalY); 
animation.duration = 1.0; 

// Use the name of the animated property as key 
// to override the implicit animation 
[layer addAnimation:animation forKey:@"position"]; 

雖然它是不適合你正在嘗試條形圖動畫完全匹配,你可以很可能會得到從上面的例子中的模式。 You can read more about it here.它幫助我解決了前幾天發生的類似問題。

相關問題