我遇到過類似的問題。我爲動畫使用了圖層而不是視圖。你可以嘗試這樣的事情。
- 將每個元素繪製爲一個CALayer,並將它們包含爲您的容器UIVIew圖層的子圖層。 UIViews更容易生成動畫,但是你的控制更少。請注意,對於任何視圖,您可以使用[視圖圖層]獲取圖層;
- 爲您的四邊形創建自定義子圖層。此圖層應具有一個或多個要爲此圖層設置動畫的屬性。我們稱這個屬性爲「customprop」。因爲它是一個自定義圖層,所以您想要在動畫的每個幀上重新繪製。對於您計劃設置動畫的屬性,您的自定義圖層類應返回YES needsDisplayForKey :.這樣你確保- (void)drawInContext:(CGContextRef)theContext在每一幀被調用。
- 將所有動畫(圓圈和四邊形)放在同一個事務中;
對於圓你大概可以使用CALayers並設置內容,如果它是一個圖像,以標準方式:
layer.contents = [UIImage imageNamed:@"circle_image.png"].CGImage;
現在,對於四層,子類的CALayer和實施這種方式:
- (void)drawInContext:(CGContextRef)theContext{
//Custom draw code here
}
+ (BOOL)needsDisplayForKey:(NSString *)key{
if ([key isEqualToString:@"customprop"])
return YES;
return [super needsDisplayForKey:key];
}
交易看起來像:
[CATransaction begin];
CABasicAnimation *theAnimation=[CABasicAnimation animationWithKeyPath:@"customprop"];
theAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(1000, 1000)];
theAnimation.duration=1.0;
theAnimation.repeatCount=4;
theAnimation.autoreverses=YES;
theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
theAnimation.delegate = self;
[lay addAnimation:theAnimation forKey:@"selecting"];
[CATransaction setValue:[NSNumber numberWithFloat:10.0f]
forKey:kCATransactionAnimationDuration];
circ1.position=CGPointMake(1000, 1000);
circ2.position=CGPointMake(1000, 1000);
[CATransaction commit];
現在所有的繪圖程序都會同時發生。確保你的drawInContext:實現速度很快。否則動畫會滯後。
將每個子圖層添加到UIViews圖層後,請記住調用[layer setNeedsDisplay]。它不會自動調用。
我知道這有點複雜。但是,生成的動畫要比使用NSTimer並在每次調用時重新繪製更好。
正如我所提到的,我已經嘗試過使用presentationLayer,但它落後於圓圈。我需要一個更可靠的方法來同步多個組件的動畫。 – titaniumdecoy 2010-11-29 22:23:32
我能想到的唯一可靠的方法是綁定到動畫機器中。你可以看看使用CAShapeLayer並將其路徑與圓圈同步製作。 – 2010-11-30 02:53:45