在Xcode 4.3.2中使用适用于iPhone 5.1的Obj.-c;我创建了一个CALayers数组,全部来自同一图像。 然后,我希望通过CATransactions分组,同时将CABasicAnimation应用于数组中的每个CALayer。 这一切都是一次性的。 但是,我想反复调用 CABasicAnimation 块,这些块包含在 CATransactions 中,但能够在每次同时执行块时单独修改每个动画的属性。 例如,我有动画的 from 和 to 值,我想每次为每个图层上的动画随机更改这些值。 因为我想重复相同的基本动画,但进行属性修改;将动画的 repeatCount 属性设置为某个高值将不起作用。我尝试在makeSwarm方法中使用for循环反复调用animate方法,使用animationDidStop来诱导另一次对animate方法的调用,但最终发生的事情是使用CATransaction块而不是在末尾进行新调用,并且还具有方法调用本身(将[self animate];放在animate方法的末尾);这些都不起作用。 这是基本代码。 我认为这很简单,但我没有看到重要的东西。谢谢,赛斯
视图控制器.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
视图控制器.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];
}
我已经为自己回答了这个问题。我在循环结束时(当 i==2 时)和动画结束时(指示循环结束)设置动画委托,然后从 animationDidStop 方法再次调用该方法 animate。如果有比这更优雅或更无故障的解决方案,我会全力以赴,并会接受它作为答案。