iPad: Move UIView with animation, then move it back - iphone

I have the following code in a UIView subclass that will move it off the screen with an animation:
float currentX = xposition; //variables that store where the UIView is located
float currentY = yposition;
float targetX = -5.0f - self.width;
float targetY = -5.0f - self.height;
moveX = targetX - currentX; //stored as an instance variable so I can hang on to it and move it back
moveY = targetY - currentY;
[UIView beginAnimations:#"UIBase Hide" context:nil];
[UIView setAnimationDuration:duration];
self.transform = CGAffineTransformMakeTranslation(moveX,moveY);
[UIView commitAnimations];
It works just great. I've changed targetX/Y to 0 to see if it does indeed move to the specified point, and it does.
The problem is when I try and move the view back to where it was originally:
moveX = -moveX;
moveY = -moveY;
[UIView beginAnimations:#"UIBase Show" context:nil];
[UIView setAnimationDuration:duration];
self.transform = CGAffineTransformMakeTranslation(moveX,moveY);
[UIView commitAnimations];
This puts the UIView about 3x as far as it should. So the view usually gets put off the right side of the screen (depending on where it is).
Is there something with the CGAffineTransforMakeTranslation function that I should know? I read the documentation, and from what I can tell, it should be doing what I'm expecting it to do.
Anyone have a suggestion of how to fix this? Thanks.

Assigning to a transform will cause the old one to disappear. To return to the original position, assign the identity transform to it.
self.transform = CGAffineTransformIdentity;
(Or better, just change the .frame instead of changing the .transform.)

UIView transform isn't additive; I suggest that to move it back you instead do:
self.transform = CGAffineTransformIdentity;
The docs say (about updating the frame):
"Warning: If this property is not the identity transform, the value of the frame property is undefined and therefore should be ignored."

Related

"Push" animation in Objective-C

I have two views: A and B. A is positioned at the top of the screen, B is positioned at the bottom of the screen.
When the user presses a button, view B animates upwards with a EaseInEaseOut bezier curve until it reaches y = 0. While B is on its way to its destination, it should push A up when it hits A. In other words, when B has passed a certain y coordinate (A's y origin + height) during its transition from bottom to top, A should stick to B so it seems B pushes A upwards.
What I have tried so far:
Register a target + selector to a CADisplayLink immediately after the user pressed the button. Inside this selector, request view B's y coordinate by accessing its presentationLayer and adjust A's y coordinate accordingly. However, this method turns out to be not accurate enough: the presentationLayer's frame is behind on B's current position on the screen (this is probably because -presentationLayer recalculates the position of the animating view on the current time, which takes longer than 1 frame). When I increase B's animation duration, this method works fine.
Register a target + selector to a CADisplayLink immediately after the user pressed the button. Inside this selector, calculate B's current y coordinate by solving the bezier equation for x = elapsed time / animation duration (which should return the quotient distance traveled / total distance). I used Apple's open source UnitBezier.h for this (http://opensource.apple.com/source/WebCore/WebCore-955.66/platform/graphics/UnitBezier.h). However, the results are not correct.
Any suggestions on what I can try next?
Two simple solutions:
Use animationWithDuration only: You can break your animation into two nested animations, using "ease in" to animate the moving of "B" up to "A", and then using "ease out" to animate the moving of "B" and "A" the rest of the way. The only trick here is to make sure the two duration values make sense so that the speed of the animation doesn't appear to change.
CGFloat animationDuration = 0.5;
CGFloat firstPortionDistance = self.b.frame.origin.y - (self.a.frame.origin.y + self.a.frame.size.height);
CGFloat secondPortionDistance = self.a.frame.size.height;
CGFloat firstPortionDuration = animationDuration * firstPortionDistance / (firstPortionDistance + secondPortionDistance);
CGFloat secondPortionDuration = animationDuration * secondPortionDistance / (firstPortionDistance + secondPortionDistance);
[UIView animateWithDuration:firstPortionDuration
delay:0.0
options:UIViewAnimationOptionCurveEaseIn
animations:^{
CGRect frame = self.b.frame;
frame.origin.y -= firstPortionDistance;
self.b.frame = frame;
}
completion:^(BOOL finished) {
[UIView animateWithDuration:secondPortionDuration
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^{
CGRect frame = self.b.frame;
frame.origin.y -= secondPortionDistance;
self.b.frame = frame;
frame = self.a.frame;
frame.origin.y -= secondPortionDistance;
self.a.frame = frame;
}
completion:nil];
}];
You can let animateWithDuration handle the full animation of "B", but then use CADisplayLink and use presentationLayer to retrieve B's current frame and to adjust A's frame accordingly:
[self startDisplayLink];
[UIView animateWithDuration:0.5
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
CGRect frame = self.b.frame;
frame.origin.y = self.a.frame.origin.y;
self.b.frame = frame;
}
completion:^(BOOL finished) {
[self stopDisplayLink];
}];
where the methods to start, stop, and handle the display link are defined as follows:
- (void)startDisplayLink
{
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:#selector(handleDisplayLink:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)stopDisplayLink
{
[self.displayLink invalidate];
self.displayLink = nil;
}
- (void)handleDisplayLink:(CADisplayLink *)displayLink
{
CALayer *presentationLayer = self.b.layer.presentationLayer;
if (presentationLayer.frame.origin.y < (self.a.frame.origin.y + self.a.frame.size.height))
{
CGRect frame = self.a.frame;
frame.origin.y = presentationLayer.frame.origin.y - self.a.frame.size.height;
self.a.frame = frame;
}
}
You said that you tried the "animate B and use display link to update A" technique, and that it resulted in "A" lagging behind "B". You could theoretically animate a new view, "C", and then adjust B and A's frames accordingly in the display link, which should eliminate any lag (relative to each other).
You can try followin algorythm:
1)Put A and B in UIView(i.e UIview *gropedView)
2)Change B.y till it will be equal A.y+A.height(so B will be right under the A)
3)Animate groupedView

Current value of rotation during a animateWithDuration

I'm using animateWithDuration to have one of my UIVIew rotating endlessly. Now, I need to get the current value of my UIView's rotation at a specific time.
I've tried to use the following function :
-(float)getCurrentRotation{
CGAffineTransform transform = ((UIImageView*)[self.subviews objectAtIndex:0]).transform;
return (atan2(transform.b, transform.a));
}
but it always returns the same value (M_PI/2) as it's the value I've specified in my initial call to animateWithDuration :
[UIView animateWithDuration:4 delay:0 options:( UIViewAnimationOptionRepeat|UIViewAnimationOptionCurveLinear) animations:^{
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
((UIImageView*)[self.subviews objectAtIndex:0]).transform = transform;
}
completion:^(BOOL finished){
}];
Is there a way to have the current value of the rotation ?
Thanks.
When using CoreAnimation based animation, your view properties (bounds, transform...) never actually change. What changes are the properties of the layer displayed on screen while animating (see this documentation page), which is accessible using view.layer.presentationLayer.
Thus, the following line will get you the actual transform at the time you ask for it:
CGAffineTransform transform = CATransform3DGetAffineTransform([(CALayer*)[[[self.subviews objectAtIndex:0] layer] presentationLayer] transform]);
You must link against and include the QuartzCore framework, which defines CALayer, for this to work.
#import <QuartzCore/QuartzCore.h>
I'm not sure if it's possible to watch the "value of the rotation" while it is shown on screen. But I'd say it is not, because your view object does have the new property value immediately and the animation takes place somewhere deep inside the framework on objects you're not able to reach.
To fulfill your goal I'd separate the rotation into single steps with a granularity sufficient for your needs. Then just count the steps and make the current step available. Could look a bit like this (not tested, just a scribble):
//step and rotator declared as class members
//rotator is the one which is referred to as ((UIImageView*)[self.subviews objectAtIndex:0]) in the original question
-(CGFloat)currentRotation
{
return step*(M_PI/16);
}
-(void)turnturnturn
{
[UIView animateWithDuration:0.2
animations:^
{
rotator.transform = CGAffineTransformConcat(CGAffineTransformMakeRotation(M_PI/16), rotator.transform);
step++;
}
completion:^(BOOL finished)
{
if(step == 32)
{
step = 0;
rotator.transform = CGAffineTransformIdentity;
}
[self turnturnturn];
}];
}

CGAffineRotation Skews Image Photos

My iOS has registered for device orientation change notifications via NSNotificationCenter, and has a method that responds to the different orientation changes. The following code is called to change the orientation and location of a view when rotating the phone to "landscape-left".
camAngle = [(NSNumber *)[_cameraToggleButton valueForKeyPath:#"layer.transform.rotation.z"] floatValue];
camDegrees = (RADIANS_TO_DEGREES(camAngle));
if (!(camDegrees == 90)) {
_cameraToggleButton.alpha = 0.0;
_cameraToggleButton.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(90));
_cameraToggleButton.frame = CGRectMake(274, 350, 66, 54);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.4];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
_cameraToggleButton.alpha = 1.0;
[UIView commitAnimations];
}
And my equations to convert radians and degrees:
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
The view rotates correctly and assumes the correct position on screen, but the sides of the image are suddenly squashed, making the image look condensed. This only happens when rotating the phone into landscape position (left or right). Rotating to upside down or back to portrait translates and rotates the view fine, with essentially the same code. What could cause this skewing of the images in landscape position?
You should not set the frame of the _cameraToggleButton after you set the rotation transform on it. To re-position the _cameraToggleButton after you set the rotation, you should change it's center like so:
_cameraToggleButton.center = CGPointMake(274, 350);
Also, as someone else suggested, use UIViewContentModeScaleAspectFit instead of UIViewContentModeScaleToFill.

CGRect not changing during animation

I'm animating an UIView and want to check if its frame intersects with another UIView's frame. This is how I "spawn" one of the UIViews:
- (void) spawnOncomer
{
oncomer1 = [[Oncomer alloc] initWithType:#"car"];
[self.view addSubview:oncomer1];
//make the oncomer race across the screen
[UIView beginAnimations:nil context:NULL]; {
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:3.0];
[UIView setAnimationDelegate:self];
CGRect f = oncomer1.frame;
f.origin.y = self.view.frame.size.height+oncomer1.frame.size.height;
oncomer1.frame = f;
[UIView setAnimationDidStopSelector:#selector(decountCar)];
}
[UIView commitAnimations];
}
So far so good. Now I want to check if this UIView and my other UIView collide by doing this:
- (void) checkCollision {
bool collision = CGRectIntersectsRect(car.frame, oncomer1.frame);
if (collision) {
NSLog(#"BOOOOOOOM");
} else {
NSLog(#"Oncomer: %#", NSStringFromCGRect(oncomer1.frame));
}
}
However, they never collide. Although I see oncomer1 moving across the screen, loggin oncomer1.frame never changes: it keeps outputting Oncomer: {{50, 520}, {30, 60}}(which are the post-animation values).
Does anyone know why this is?
P.s. Both methods are called directly or indirectly with a NSTimer and are thus performed in the background
UIView geometry updates apply immediately to their CALayer, even in an animation block. To get a version of a layer with animations applied, you can use -[CALayer presentationLayer], like this (warning - untested code):
- (void) checkCollision {
CGRect oncomerFrame = oncomer1.layer.presentationLayer.frame;
bool collision = CGRectIntersectsRect(car.frame, oncomerFrame);
if (collision) {
NSLog(#"BOOOOOOOM");
} else {
NSLog(#"Oncomer: %#", NSStringFromCGRect(oncomerFrame));
}
}
From your code:
CGRect f = oncomer1.frame;
f.origin.y = self.view.frame.size.height+oncomer1.frame.size.height;
oncomer1.frame = f;
A logical explanation of the frame never changing is that you are only changing the y of the frame, and you are always setting it to the same value determined by two heights.

need to create a restore point (to save the current image position)

how do i create a restore point (to save the current position for restarting the animation later) for the say1 object (s and also how to call it.
thanks.
- (void) doneThing {
say1.hidden = FALSE;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.4];
CGPoint destination = CGPointMake(152,-20);
say.center = destination;
[UIView commitAnimations];
}
Just store its location in an instance variable.