所以我第一次尝试CABasicAnimation。我试图将它应用于一个图层,我希望图层从一个点插入到另一个点。我最初设置一个负x坐标,我把动画放在无限。它正在工作但是它需要几秒钟才能出现在屏幕上。所以它应该完全走到尽头并重新开始。以下是代码
[[self bgImageView] setImage:[UIImage imageNamed:@"bg_dynamicwx_cloudyday_3.jpg"]];
for (CALayer *layer in self.emitterView.layer.sublayers) {
[layer removeAllAnimations];
}
[self.emitterView.layer removeAllAnimations];
NSArray *subLayers = self.emitterView.layer.sublayers;
for (CALayer *layer in subLayers) {
[layer removeFromSuperlayer];
}
CALayer *mask = [CALayer layer];
UIImage *layerImg = [UIImage imageNamed:@"2_cloud.png"];
mask.bounds = CGRectMake(self.emitterView.bounds.origin.x, self.emitterView.bounds.origin.y, layerImg.size.width, layerImg.size.height);
mask.contents = (id)layerImg.CGImage;
CGPoint fromPoint = CGPointMake(-layerImg.size.width, 0);
CGPoint toPoint = CGPointMake(layerImg.size.width, 0);
mask.position = fromPoint; // CoreAnimation animations do *not* persist
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromPoint];
animation.toValue = [NSValue valueWithCGPoint:toPoint];
animation.duration = 150;
animation.repeatCount = INFINITY;
[mask addAnimation:animation forKey:@"position"];
[self.emitterView.layer addSublayer:mask];
基本上我正在尝试云动画,云在屏幕上浮动。我很确定我的基本动画有一些错误概念。由于持续时间是150(它应该是微妙的),显示动画需要永远。似乎位置比我给出的更多是在屏幕外。我用于图层的图像是728乘368。
答案 0 :(得分:1)
position属性位于图层的中间。
您使用的代码假定该位置位于图层的左上角。您可以通过更改您的往返点来轻松解决此问题:
CGPoint fromPoint = CGPointMake(-layerImg.size.width*0.5, layerImg.size.height*0.5);
CGPoint toPoint = CGPointMake(layerImg.size.width*1.5, layerImg.size.height*0.5);
现在,您的图层将从屏幕外左侧移动到屏幕右侧。