在Xcode 4.3.2中使用iPhone 5.1的Obj.-c;我創建了一組CALayers,全部來自同一圖像。然後我希望通過CATransactions進行分組,同時將CABasicAnimation應用於陣列中的每個CALayer。這一切都有效。但是,我想重複調用CATransactions中包含的CABasicAnimations塊,但每次同時執行塊時,都可以單獨修改每個動畫的屬性。舉例來說,我從每個層次上的動畫每次隨機更改動畫的值和值。因爲我想重複相同的基本動畫,但是需要修改屬性;將動畫的repeatCount屬性設置爲某個較高的值將不起作用。我嘗試過使用makeSwarm方法中的for循環重複調用animate方法,使用animationDidStop引發另一個動畫方法調用,但最終發生的是新調用使用CATransaction塊創建,而不是在最後,並且也有方法調用自己(put [self animate];在animate方法結束時);並且這些都不起作用。這是基本的代碼。我認爲這很簡單,但我沒有看到重要的東西。謝謝,塞思如何循環包含在CATransaction塊中的幾個CABasicAnimations?
的ViewController.h
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
UIImage *beeImage;
UIImageView *beeView;
CALayer *beeLayer;
CABasicAnimation *animat;
NSMutableArray *beeArray;
NSMutableArray *beeanimArray;
}
@property(retain,nonatomic) UIImage *beeImage;
@property(retain,nonatomic) NSMutableArray *beeArray;
@property(retain,nonatomic) NSMutableArray *beeanimArray;
@property(retain,nonatomic) UIImageView *beeView;
@property(retain,nonatomic) CALayer *beeLayer;
@property(retain,nonatomic)CABasicAnimation *animat;
-(void) animate;
-(void) makeSwarm;
@end
的ViewController.m
-(void) makeSwarm{
self.view.layer.backgroundColor = [UIColor orangeColor].CGColor;
self.view.layer.cornerRadius = 20.0;
self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);
CGRect beeFrame;
beeArray = [[NSMutableArray alloc] init];
beeImage = [UIImage imageNamed:@"bee50x55px.png"];
beeFrame = CGRectMake(0, 0, beeImage.size.width, beeImage.size.height);
int i;
CALayer *p = [[CALayer alloc] init];
for (i = 0; i < 3; i++) {
beeView = [[UIImageView alloc] initWithFrame:beeFrame];
beeView.image = beeImage;
beeLayer = [beeView layer];
[beeArray addObject: beeLayer];
p = [beeArray objectAtIndex: i];
[p setPosition:CGPointMake(arc4random()%320, arc4random()%480)];
[self.view.layer addSublayer:p];
}
[self animate];
}
-(void)animate
{
//the code from here to the end of this method is what I would like to repeat as many times as I would like
[CATransaction begin];
int i;
for (i = 0; i < 3; i++) {
animat = [[CABasicAnimation alloc] init];
[animat setFromValue:[NSValue valueWithCGPoint:CGPointMake(arc4random()%320, arc4random()%480)]];
animat.toValue = [NSValue valueWithCGPoint:CGPointMake(arc4random()%320, arc4random()%480)];
[animat setFillMode:kCAFillModeForwards];
[animat setRemovedOnCompletion:NO];
animat.duration=1.0;
CALayer *p = [[CALayer alloc] init];
p = [beeArray objectAtIndex: i];
[p addAnimation:animat forKey:@"position"];
}
[CATransaction commit];
}
我相信我已經爲自己回答了這個問題。我在循環結束時設置動畫的委託(當我== 2),當動畫結束(指示循環結束),然後從animationDidStop方法,然後再次調用方法動畫。如果有比這更優雅或者無故障的解決方案,我會全神貫注,並且會接受它作爲答案。 – 2012-04-14 21:39:40