Hey im trying to show the y axis of my imageview while its moving , but its not displaying the animating y axis , its showing only one number .
//LINE ANAMATION
CALayer *layer = line.layer;
CGPoint startPoint = (CGPoint){line.center.x,20};
CGPoint endPoint = (CGPoint){line.center.x, screenSizeY/2};
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath, NULL, startPoint.x, startPoint.y);
CGPathAddLineToPoint(thePath, NULL, endPoint.x, endPoint.y);
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
animation.duration = 3.f;
animation.path = thePath;
animation.autoreverses = YES;
animation.repeatCount = INFINITY;
[layer addAnimation:animation forKey:#"position"];
NSLog(#"%f", line.center.y);
There are a couple of things wrong with this. First, the animation state is maintained in the presentation layer. Your view and underlying layer are will reflect the final state of the animation immediately. Second, your NSLog statement will only be called once because you aren't in a loop.
If you want to do something at each frame of an animation, you can use CADisplayLink to get a callback on each frame. In this callback, you can check the current Y position by looking at the presentation layer:
- (void)myCallback:(CADisplayLink *)link
{
NSLog(#"%f", CGRectGetMidY(line.layer.presentationLayer.frame));
}
Related
So I am trying CABasicAnimation for the very first time. I am trying to apply it on a layer and I want layer to interpolate from one point to another. I initially set a negative x coordinate and I put the animation on the infinite. It is working but then it takes few seconds to appear on screen. So it should completely go to the end and start again. Following is code
[[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];
Basically I'm trying the cloud animation, where the cloud is floating over the screen. I'm pretty sure I got some concept wrong here for basic animation. As the duration is 150 (it is supposed to be subtle), it takes forever to show up the animation. Seems like position is offscreen by more than what I have given. Image I am using for the layer is 728 by 368.
From the documentation:
The position property is located in the middle of the layer.
The code you're using assumes that position is located at the top left of the layer. You can easily fix this by changing your to and from points:
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);
Now your layer will animate from off-screen left to off-screen right.
So im new to objective-c and i have a image that's moving up and down the screen at all times , how would i code if another image touches or intercepts that image . this is the animation code i have done , but still confused on how to write the second part. thank you for your help
Animation:
//LINE ANAMATION
layer = line.layer;
CGPoint startPoint = (CGPoint){line.center.x,20};
CGPoint endPoint = (CGPoint){line.center.x, screenSizeY/2};
CGMutablePathRef thePath = CGPathCreateMutable();
CGPathMoveToPoint(thePath, NULL, startPoint.x, startPoint.y);
CGPathAddLineToPoint(thePath, NULL, endPoint.x, endPoint.y);
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
animation.duration = 3.f;
animation.path = thePath;
animation.autoreverses = YES;
animation.repeatCount = INFINITY;
[layer addAnimation:animation forKey:#"position"];
Try:
if (CGRectIntersectsRect(self.imageView1.frame, self.imageView2.frame))
{
NSLog(#"Intersected!");
}
else
{
NSLog(#"No intersection :(");
}
I'm trying to animate many bubbles coming out of a machine. I'm using a basic animation to scale the bubbles from a small bubble to a large one and a keyframe animation to send the bubble in a curve across the screen. These are combined into a group animation.
I have read through just about all I can to try to get this to work, but I have the following two problems.
I can't get the scale animation to work together with the keyframe
animation when I try to animate each bubble.
The animation happens to them all at the same time. I'd like to see them animated one
after the other, but they all animate together.
here is the animation code I have.
-(void)EmitBubbles:(UIButton*)bubblename :(CGRect)RectPassed
{
bubblename.hidden = NO;
// Set position and size of each bubble to be at head of bubble machine and size (0,0)
CGPoint point = (RectPassed.origin);
CGRect ButtonFrame;
ButtonFrame = bubblename.bounds;
ButtonFrame.size = CGSizeMake(0, 0);
bubblename.bounds = ButtonFrame;
CGRect OldButtonBounds = bubblename.bounds;
CGRect NewButtonBounds = OldButtonBounds;
NewButtonBounds.size = RectPassed.size;
CGFloat animationDuration = 0.8f;
// Set up scaling
CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:#"bounds.size"];
resizeAnimation.fillMode = kCAFillModeForwards;
resizeAnimation.duration = animationDuration;
resizeAnimation.fromValue = [NSValue valueWithCGSize:OldButtonBounds.size];
resizeAnimation.toValue = [NSValue valueWithCGSize:NewButtonBounds.size];
// Set Actual bubble size after animation
bubblename.bounds = NewButtonBounds;
// Setup Path
CGPoint MidPoint = CGPointMake(500,50);
CGPoint EndPoint = CGPointMake(RectPassed.origin.x, RectPassed.origin.y);
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, nil, bubblename.bounds.origin.x, bubblename.bounds.origin.y);
CGPoint NewLoc = CGPointMake(745, 200);
CGPathMoveToPoint(curvedPath, NULL, NewLoc.x,NewLoc.y);
CGPathAddCurveToPoint(curvedPath, NULL, 745,200,MidPoint.x,MidPoint.y, EndPoint.x, EndPoint.y);
pathAnimation.path = curvedPath;
// Set Bubble action position after animation
bubblename.layer.position = point;
// Add scale and path to animation group
CAAnimationGroup *group = [CAAnimationGroup animation];
group.removedOnCompletion = YES;
[group setAnimations:[NSArray arrayWithObjects:pathAnimation, resizeAnimation, nil]];
group.duration = animationDuration;
[bubblename.layer addAnimation:group forKey:#"nil"]; //savingAnimation
CGPathRelease(curvedPath);
}
I call the animation for each bubble using
[self EmitBubbles:btnbubble1 :CGRectMake(200, 500, 84, 88)];
[self EmitBubbles:btnbubble2 :CGRectMake(200, 500, 84, 88)];
I have 20 bubbles on screen. The size of the rect passed is the final size I want the bubbles to be.
Can I can get each bubble to animate separately using a scale and keyframe path, without having to write the above code for each bubble?
Thanks
OK. I think I did it.After hours of looking around Stackoverflow and other places I found that to bhave the objects animate one after the other. I had to calculate the time according to the app time. I used.
group.beginTime = CACurrentMediaTime() + AnimationDelay
To stop the animation momentarily appearing at its final position before continuing with the animation. I had to use
group.fillMode = kCAFillModeBackwards;
I have a custom CALayer that I am animating using a CAAnimationGroup to follow a path and rotate at a tangent to the path:
// Create the animation path
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
//Setting Endpoint of the animation
CGRect contentBounds = [self contentBounds];
self.boatLayer.bounds = contentBounds;
CGPoint endPoint = CGPointMake(contentBounds.size.width - 150, contentBounds.size.height - 150);
CGMutablePathRef curvedPath = CGPathCreateMutable();
CGPathMoveToPoint(curvedPath, NULL, startPosition.x, startPosition.y);
CGPathAddCurveToPoint(curvedPath, NULL, endPoint.x, 0, endPoint.x, 0, endPoint.x, endPoint.y);
pathAnimation.path = curvedPath;
pathAnimation.duration = 10.0;
pathAnimation.rotationMode = kCAAnimationRotateAuto;
pathAnimation.delegate = self;
// Create an animation group of all the animations
CAAnimationGroup *animationGroup = [[[CAAnimationGroup alloc] init] autorelease];
animationGroup.animations = [NSArray arrayWithObjects:pathAnimation, nil];
animationGroup.duration = 10.0;
animationGroup.removedOnCompletion = NO;
// Add the animations group to the layer (this starts the animation at the next refresh cycle)
[testLayer addAnimation:animationGroup forKey:#"animation"];
I need to be able to track the changes to the position and rotation of the layer as it progresses along the path. I have overridden both setPosition and setTransform (calling super setPosition and super setTranform) and then logging their values. Neither of these values appear to be set during the animation.
How can I get the position and rotation updates from within the CALayer class itself as it animates?
Core Animation doesn't work like that
Sorry. That is not how Core Animation work. When you add an animation to a layer it doesn't change the model of that layer. Only the presentation.
When you configure then animation to not remove itself upon completion
yourAnimation.fillMode = kCAFillModeForwards;
tourAnimation.removedOnCompletion = NO;
you are actually causing an inconsistency between what is shown on screen and the model of that layer. If you for instance had a button that you animated like this you would get very surprised/angry by the fact that it "no longer responds to toucher" or even more funny "responds to touches from it's 'old' location".
Semi-solutions
Depending on what and how often you actually need the updates you could either periodically check the value of the presentationLayer during the animation or use a CADisplayLink to run some code when the screen changes.
I am trying to achieve an animation that when you hold down a button it animates a block down, and when you release, it animates it back up to the original position, but I cannot obtain the current position of the animating block no matter what. Here is my code:
-(IBAction)moveDown:(id)sender{
CGRect position = [[container.layer presentationLayer] frame];
[movePath moveToPoint:CGPointMake(container.frame.origin.x, position.y)];
[movePath addLineToPoint:CGPointMake(container.frame.origin.x, 310)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
moveAnim.fillMode = kCAFillModeForwards;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil];
animGroup.duration = 2.0;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
[container.layer addAnimation:animGroup forKey:nil];
}
-(IBAction)moveUp:(id)sender{
CGRect position = [[container.layer presentationLayer] frame];
UIBezierPath *movePath = [UIBezierPath bezierPath];
[movePath moveToPoint:CGPointMake(container.frame.origin.x, position.y)];
[movePath addLineToPoint:CGPointMake(container.frame.origin.x, 115)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = NO;
moveAnim.fillMode = kCAFillModeForwards;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil];
animGroup.duration = 2.0;
animGroup.removedOnCompletion = NO;
animGroup.fillMode = kCAFillModeForwards;
[container.layer addAnimation:animGroup forKey:nil];
}
But the line
CGRect position = [[container.layer presentationLayer] frame];
is only returning the destination position not the current position. I need to basically give me the current position of the container thats animating once I release the button, so I can perform the next animation. What I have now does not work.
I haven't analyzed your code enough to be 100% sure why [[container.layer presentationLayer] frame] might not return what you expect. But I see several problems.
One obvious problem is that moveDown: doesn't declare movePath. If movePath is an instance variable, you probably want to clear it or create a new instance each time moveDown: is called, but I don't see you doing that.
A less obvious problem is that (judging from your use of removedOnCompletion and fillMode, in spite of your use of presentationLayer) you apparently don't understand how Core Animation works. This turns out to be surprisingly common, so forgive me if I'm wrong. Anyway, read on, because I will explain how Core Animation works and then how to fix your problem.
In Core Animation, the layer object you normally work with is a model layer. When you attach an animation to a layer, Core Animation creates a copy of the model layer, called the presentation layer, and the animation changes the properties of the presentation layer over time. An animation never changes the properties of the model layer.
When the animation ends, and (by default) is removed, the presentation layer is destroyed and the values of the model layer's properties take effect again. So the layer on screen appears to “snap back” to its original position/color/whatever.
A common, but wrong way to fix this is to set the animation's removedOnCompletion to NO and its fillMode to kCAFillModeForwards. When you do this, the presentation layer hangs around, so there's no “snap back” on screen. The problem is that now you have the presentation layer hanging around with different values than the model layer. If you ask the model layer (or the view that owns it) for the value of the animated property, you'll get a value that's different than what's on screen. And if you try to animate the property again, the animation will probably start from the wrong place.
To animate a layer property and make it “stick”, you need to change the model layer's property value, and then apply the animation. That way, when the animation is removed, and the presentation layer goes away, the layer on screen will look exactly the same, because the model layer has the same property values as its presentation layer had when the animation ended.
Now, I don't know why you're using a keyframe to animate straight-line motion, or why you're using an animation group. Neither seems necessary here. And your two methods are virtually identical, so let's factor out the common code:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromValue];
animation.toValue = [NSValue valueWithCGPoint:toValue];
animation.duration = 2;
[layer addAnimation:animation forKey:animation.keyPath];
}
Notice that we're giving the animation a key when I add it to the layer. Since we use the same key every time, each new animation will replace (remove) the prior animation if the prior animation hasn't finished yet.
Of course, as soon as you play with this, you'll find that if you moveUp: when the moveDown: is only half finished, the moveUp: animation will appear to be at half speed because it still has a duration of 2 seconds but only half as far to travel. We should really compute the duration based on the distance to be travelled:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y withBaseY:(CGFloat)baseY {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"position"];
animation.fromValue = [NSValue valueWithCGPoint:fromValue];
animation.toValue = [NSValue valueWithCGPoint:toValue];
animation.duration = 2.0 * (toValue.y - fromValue.y) / (y - baseY);
[layer addAnimation:animation forKey:animation.keyPath];
}
If you really need it to be a keypath animation in an animation group, your question should show us why you need those things. Anyway, it works with those things too:
- (void)animateLayer:(CALayer *)layer toY:(CGFloat)y withBaseY:(CGFloat)baseY {
CGPoint fromValue = [layer.presentationLayer position];
CGPoint toValue = CGPointMake(fromValue.x, y);
layer.position = toValue;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:fromValue];
[path addLineToPoint:toValue];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
animation.path = path.CGPath;
animation.duration = 2.0 * (toValue.y - fromValue.y) / (y - baseY);
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = animation.duration;
group.animations = #[animation];
[layer addAnimation:group forKey:animation.keyPath];
}
You can find the full code for my test program in this gist. Just create a new Single View Application project and replace the contents of ViewController.m with the contents of the gist.