Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting CGPoints from one view to another relatively for an animation

Tags:

c

ios

objective-c

I'm trying to do an animation where I move one CGPoint from one view to another, I want to find the coordinates where the point is going to be in reference to the first so I can do the animation.

So let's say I have a point (24,15) in view2 and I'd like to animate it to view1, I still want to keep the value of the point within the new view as I'm adding the point as a subview of the new view, but for the animation I need to know the value of where the point would be so I can do a tween.

Please refer to this graph:

enter image description here

Now this is what I'm trying to do:

customObject *lastAction = [undoStack pop];
customDotView *aDot = lastAction.dot;
CGPoint oldPoint = aDot.center;
CGPoint  newPoint = lastAction.point;

newPoint = [lastAction.view convertPoint:newPoint toView:aDot.superview];


CABasicAnimation *anim4 = [CABasicAnimation animationWithKeyPath:@"position"];
anim4.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim4.fromValue = [NSValue valueWithCGPoint:CGPointMake(oldPoint.x, oldPoint.y )];
anim4.toValue = [NSValue valueWithCGPoint:CGPointMake( newPoint.x,  newPoint.y )];
anim4.repeatCount = 0;
anim4.duration = 0.1;
[aDot.layer addAnimation:anim4 forKey:@"position"];


[aDot removeFromSuperview];


[lastAction.view addSubview:aDot];
[lastAction.view bringSubviewToFront:aDot];

aDot.center = newPoint;

Any ideas?

like image 201
perrohunter Avatar asked Sep 06 '12 05:09

perrohunter


1 Answers

It's easier to see with block animations. I think the objective is to do the animation of a view2 subview in it's coordinate space, then, when the animation is finished, add a subview to view1 using the ending position converted into the new coordinate space.

// assume we have a subview of view2 called UIView *dot;
// assume we want to move it by some vector relative to it's initial position
// call that CGPoint offset;

// compute the end point in view2 coords, that's where we'll do the animation
CGPoint endPointV2 = CGPointMake(dot.center.x + offset.x, dot.center.y + offset.y);

// compute the end point in view1 coords, that's where we'll want to add it in view1
CGPoint endPointV1 = [view2 convertPoint:endPointV2 toView:view1];

[UIView animateWithDuration:1.0 animations:^{
    dot.center = endPointV2;
} completion:^(BOOL finished) {
    dot.center = endPointV1;
    [view1 addSubview:dot];
}];

Note that adding dot to view1 removes it from view2. Also note that if view1 should have clipsToBounds == NO if the offset vector moves the dot outside of it's bounds.

like image 140
danh Avatar answered Oct 02 '22 11:10

danh