我制作了一堆单独的小图片,每张图片都有一个单独的 CALayer,它们应该以不同的速率异步淡入和淡出。每个都有一个背景子层和一个填充子层。计时器在后台运行,以在特定时刻单独为每个人设置动画。对于程序的当前行为,它不是为每个单独的行为设置动画,而是为它周围的整个屏幕设置动画。您能帮我制作它,以便一次只为一张图像设置动画吗?
编辑:我应该更清楚。时机不是问题。在我切换到 CoreAnimation 之前,这些图像会在适当的时间正确地进行动画处理。但这里的主要问题是,当我告诉一个图像动画时,整个屏幕,包括所有图像之外的屏幕背景部分,都会被动画化。
以下代码段用于在 UIView 代码中创建分层结构。Self 指的是主 UIView。返回值用于为代表屏幕上这些小图像之一的类设置 CALayer 成员变量。
- (CALayer *) createImageLayer:(CGPoint)orig Center:(CGPoint)pos {
CALayer *parentLayer = [self layer];
CALayer *childLayer1 = [CALayer layer];
childLayer1.bounds = CGRectMake(0, 0, 40.0f, 40.0f);
childLayer1.position = pos;
CALayer *childLayer2 = [CALayer layer];
childLayer2.bounds = CGRectMake(0, 0, 40.0f, 40.0f);
childLayer2.position = pos;
float components[4] = {1.0, 1.0, 1.0, 1.0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef whiteColor = CGColorCreate( colorSpace, components);
childLayer1.backgroundColor = whiteColor;
childLayer2.backgroundColor = whiteColor;
UIImage *childImage = [UIImage imageNamed:@"back.png"];
UIImage *childImage2 = [UIImage imageNamed:@"fill.png"];
CGImageRef imageRef = [childImage CGImage];
CGImageRef imageRef2 = [childImage2 CGImage];
childLayer1.contents=(id)imageRef;
childLayer2.contents=(id)imageRef2;
[parentLayer addSublayer:childLayer1];
[parentLayer addSublayer:childLayer2];
CGColorSpaceRelease(colorSpace);
CGColorRelease(whiteColor);
return parentLayer;
}
告诉它动画的代码。图像对象被告知将动画添加到其图层成员。
- (void) fadeAnimation:(ImageClass *)image {
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=1.0; // fixed duration for now
theAnimation.repeatCount=1;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
theAnimation.toValue=[NSNumber numberWithFloat:0.0];
[image.myLayer addAnimation:theAnimation forKey:@"animateOpacity"];
}