在 Xcode 4.3.2 中为 iPhone 5.1 使用 Obj.-c;我创建了一个 CALayers 数组,所有这些都来自同一个图像。然后我希望通过 CATransactions 分组同时将 CABasicAnimation 应用于数组中的每个 CALayer。这一切都奏效了。但是,我想重复调用 CATransactions 中包含的 CABasicAnimations 块,但能够在每次同时执行块时单独修改每个动画的属性。例如,我希望每次为每一层上的动画随机更改动画的 from 和 to 值。因为我想重复相同的基本动画,但进行属性修改;将动画的 repeatCount 属性设置为某个高值将不起作用。我尝试在 makeSwarm 方法中使用 for 循环反复调用 animate 方法,使用 animationDidStop 来引发另一个 animate 方法调用,但最终发生的是使用 CATransaction 块而不是在末尾进行新调用,并且还有方法调用本身(将 [self animate]; 放在 animate 方法的末尾);而这些都不起作用。这是基本代码。我认为这很简单,但我没有看到重要的东西。谢谢,赛斯 但我没有看到重要的东西。谢谢,赛斯 但我没有看到重要的东西。谢谢,赛斯
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];
}