Simple Animation with NSTimer and opacity for the iPhone - iphone

I just want to realize a simple animation, where a picture is faded in a few seconds after the beginning of the application and then it should be faded out and totally disappear. I've never done any animations on the iPhone so I'm stuck. When using something like image.opacity = 1.0; like in the Developer Documentation I get error:
request for member 'opacity' in something not a structure or union.

To fade out an image, you want code like:
[UIView beginAnimations];
myImageView.opacity = 0.0;
[UIView commitAnimations];
You're not setting the opacity of the image itself so much as the opacity of the UIImageView (in this example myImageView) containing the image. You can also control the duration of the animation by adding a line:
[UIView setAnimationDuration: 1.5];
between the calls to -beginAnimations and -commitAnimations.

What you are looking for is the property "alpha", as in view.alpha. You have simply been looking for the wrong name.
Legal alpha values are from 0.0 (fully transparent) to 1.0 (fully opaque). It will do exactly what you are looking for.
Use the beginAnimations/commitAnimations paradigm referenced in the comment above.

Summarizing the other answers:
To fade out an image, you want code like:
// This line may not be necessary.
myImageView.alpha = 1.0f;
[UIView beginAnimations];
[UIView setAnimationDuration: 1.5];
myImageView.alpha = 0.0;
[UIView commitAnimations];

the solution above didn't work in my project. I had to do it like this....
**[UIView beginAnimations:#"myPic.png" context:nil];**
//You need to set the pic name
[UIView setAnimationDuration: myTimer];
_myPic.alpha = 1.0f;
_myPic.alpha = 0.0;
[UIView commitAnimations];
this is to fade out an image
regards
Philipp

It seems you want a fade in and then a fade out. But time to kick in after a duration. Not just the duration of the animations themselves.
I do not normall do stuff for iOS, so forgive me if I have the code in the wrong place.
This was tested on the simulator and in a single view application.
I added a new UIview to the ViewController's UIView and linked it to its .h file as an outlet. (named it theView)
Then added a UImageView to the new UIView (theView ) and set an image for the UImageView using the attributes inspector.
Then added code to the ViewController.m file.
The main thing I want to show you is the
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
Which invokes a method of the receiver on the current thread using the default mode after a delay.
(There are similar methods that can perform on other threads…)
I have made two methods one that fades in and one that fades out.
There are two performSelectors.
The first is called when the view loads.
The second is in the fadeIn animation block. You can place this in the viewDidLoad or after the block. But I thought it would be safer to have it where it is.
here is the .m file code.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_theView.alpha = 0.0;
[self performSelector:#selector(fadeIn) withObject:nil afterDelay:2.0];
}
- (void)fadeToBlack
{
[UIView animateWithDuration:3.0
delay:0.0
options:UIViewAnimationOptionCurveEaseIn
animations:^{_theView.alpha = 0.0;}
completion:nil];
}
- (void)fadeIn
{
[UIView animateWithDuration:3.0
delay:0.0
options:UIViewAnimationOptionCurveEaseIn
animations:^{_theView.alpha = 1.0; [self performSelector:#selector(fadeToBlack) withObject:nil afterDelay:10.0];}
completion:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I am expecting corrections here… as this is not really an area I am fully familiar with (ViewControllers) But its works ok in the sim.

Related

Customized Animation in iphone

I am creating Application which have so many Customization. Customization in the sense, I want to give new look to my application. In the part of customization I want to add THIS kind of animation inside my application.
i have searched over internet finally i found so many 3d animations. But those results are not satisfy my needs.
Suggest me some piece of code to make that animation possible.
If u provide any source code, That will be really helpful for me.
This is exactly you want.Set your view like this.
_transitionFrame is label outlet.That label is placed on your display view.
Include QuartzCore framework and define a method to convert degree to radians like this
#import <QuartzCore/QuartzCore.h>
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
In view did load Method write following code.
- (void)viewDidLoad
{
CGRect preFrame=_transitionFrame.frame;
preFrame.origin.y+=preFrame.size.height/2;
[_transitionFrame setFrame:preFrame];
[UIView beginAnimations:nil context:nil];
CATransform3D _3Dt = CATransform3DRotate(_transitionFrame.layer.transform,DEGREES_TO_RADIANS(90), 1.0, 0.0,0.0);
[UIView setAnimationRepeatAutoreverses:YES];
[UIView setAnimationRepeatCount:100];
[UIView setAnimationDuration:1];
[_transitionFrame.layer setAnchorPoint:CGPointMake(0.5, 1)];
_transitionFrame.layer.transform=_3Dt;
[UIView commitAnimations];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

animation in iphone

I am looking for some reference about the animation such that when you click on the application, it will bring you the first screen but slowly.
Does anybody know what it is please advice me on this issue. Thanks
edit
I just wanna make a nice transition after all.Whenever I click on the application, the first screen just come up. I would like to make it nicer just like the first screen is brought slowly slowly and displayed on the scree. Hope it makes sense now.
I assume you mean fading out the splash screen after the application starts? You can add something like this to applicationDidFinishLaunching to display the splash art full-screen immediately on boot, and then fade it out
UIView *topView = self.window.rootViewController.view;
bootSplashView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
bootSplashView.image = [UIImage imageNamed:#"iPhoneDefault.png"];
[topView addSubview:bootSplashView];
[self performSelector:#selector(fadeBootScreen) withObject:nil afterDelay:0];
And then in a separate method:
- (void)fadeBootScreen
{
[UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationCurveEaseIn animations:^{
bootSplashView.alpha = 0.0;
} completion:^(BOOL finished) {
[bootSplashView removeFromSuperview];
bootSplashView = nil;
}];
}
Make sure to add 'bootSplashView' as an class variable. If your app can start in different orientation (relevant on the iPad), specialize for those cases by loading a different image.
Well, this is a broad question, but I think you can try Cocos2D for this. There are a lot of examples how to use it, but one simple animation example is this: http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d
Also, there is a good book called "Learning Cocos2D" where there is a good example of managing menus and load layers. http://cocos2dbook.com/
I hope I could help.
UIView has a lot methods for animating them.
Take a look at the View Programming Guide:
http://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html#//apple_ref/doc/uid/TP40009503-CH6-SW1
The UIView documentation also has a chapter that lists the animation related methods:
http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW131
And here's an example for a block based animation, which will fade in a view using it's alpha value:
NSTimeInterval animationDuration = 0.3;
CGFloat startValue = 0.0;
CGFloat endValue = 1.0;
myView.alpha = startValue;
[UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
myView.alpha = endValue
}
completion:^(BOOL finished){
// If you need to do something additional once the animation is finished, place it here.
}];

iPhone Flip Animation using UIViewAnimationTransitionFlipFromLeft in landscape mode

I am working on one iPhone application in which I implemented one animation UIViewAnimationTransitionFlipFromLeft. Here my application works fine in the Portrait mode. It is doing the same animation as specified means Flip from Left to Right.
But when I am doing this UIViewAnimationTransitionFlipFromLeft in landscape mode then it is not rotating from left to right. Instead of it is rotating from top to bottom. This is really critical issue. Can you help me out to solve this.
The code I am using for iPhone application to rotate the view is as follows:
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:self.view.window cache:NO];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
[UIView commitAnimations];
[self.navigationController pushViewController:objSecond animated:YES];
Thanks,
Best Regards,
Gurpritsingh Saini
If you are using iOS 4.0 or later, the following will do exactly what you want (I just tested it out to make sure)
NewView *myNewView = [[NewView alloc] initWith.....];
[UIView transitionFromView:self.view toView:myNewView.view duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];
//[self.navigationController pushViewController:myNewView animated:NO];
[myNewView release];
EDIT: I'm changing the above code a bit (nothing new, just commenting out the navigation controller because it's not necessary for this).
So there are several ways to go about this (as far as keeping track of the next view), but this is the easiest I can think of. You can already switch from view 1 to 2, so I'm going to explain how to get from 2 to 10 (or however many you need).
Basically, the view transition lasts too long for viewDidLoad to catch a call to go to the next view. So what we need to do is set up a timer that waits and sends a method to switch at a later time. So this is the code you would see in view 2 (and 3 and 4, etc.).
- (void)viewDidLoad {
// this gets called before animation finishes, so wait;
self.navigationController.delegate = self;
// you will need to set the delegate so it can take control of the views to swap them;
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(switchView) userInfo:nil repeats:NO];
}
I only wait 1 second until I call the switch method, but if you are loading a lot into your views, you may want to wait a bit longer. 1.5 seconds should be more than enough, but you can play around with that to see where it works and doesn't work.
Next, you have to call the next view in the switchView method.
- (void)switchView {
NextView *myNextView = [[NextView alloc] initWith ... ];
[UIView transitionFromView:self.view toView:nextView.view duration:1 options:UIViewAnimationOptionTransitionFlipFromLeft completion:nil];
[nextView release];
}
This worked perfectly for me. Just to make sure I was getting new views, I assigned tags to each view and added UILabels as subviews in each view's viewDidLoad method and each showed the number of its view. So hopefully this is what you needed. I'm sure you have more complex things you will need to do, but this will give you the animation and logic you need to get the look you want. (on a side note, viewDidAppear doesn't seem to get called when doing this, so it might be necessary to call it manually from viewDidLoad if you really need to use it, but otherwise it works fine)
You will have to manually add a transformation to your view; the flip transformation always operates as if the view controller were in portrait orientation.
Note that the context argument to +beginAnimations:context: is not meant to be a CGContextRef per se. You probably don't want to pass the current graphics context there. Pass NULL instead.
Try with this :
CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation.y"];
CGFloat startValue = 0.0;
CGFloat endValue = M_PI;
rotateAnimation.fromValue = [NSNumber numberWithDouble:startValue];
rotateAnimation.toValue = [NSNumber numberWithDouble:endValue];
rotateAnimation.duration = 1.5;
[self.view.layer addAnimation:rotateAnimation forKey:#"rotate"];
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:self.view cache:NO];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
[UIView commitAnimations];
I think this will work out.
The Accepted answer by slev did not work for me, I got all sorts of errors after trying the code in my custom Segue. I found a method that not only works but is more precise as it doesn't require the use of a Timer. Here is MySegue.m:
#implementation FlipRightSegue
- (id)initWithIdentifier:(NSString *)iden source:(UIViewController *)sour destination:(UIViewController *)dest
{
self = [super initWithIdentifier:iden source:sour destination:dest];
return self;
}
- (void)perform
{
UIViewController *src = [self sourceViewController];
UIViewController *dst = [self destinationViewController];
//[UIView transitionFromView:src.view toView:dst.view duration:1 options:UIViewAnimationOptionTransitionFlipFromRight completion:nil];
//[UIView commitAnimations];
[UIView transitionWithView:src.navigationController.view duration:0.8 options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
[src.navigationController pushViewController:dst animated:NO];
}
completion:NULL];
}
#end
I also have a second class for flips to the right.
Code was taken from this website: http://www.dailycode.info/Blog/post/2012/11/29/iOS-Custom-Flip-Segue-(portrait-and-landscape-layout)-xcode-4.aspx

How to properly release a view after a UIView Animation ? :)

I have a method like the following:
- (void)add:(id)sender {
MyAddViewController *controller = nil;
controller = [[MyAddViewController alloc] initWithAddType:1];
//controller.delegate = self;
// Do some animation. Slide it in from the right side of the screen.
CGPoint initialCenter = self.view.center;
controller.view.center =
CGPointMake(initialCenter.x + 320, initialCenter.y);
// Add the subview now with it's center + 320 off the screen.
[self.view addSubview:controller.view];
[UIView beginAnimations:#"animation" context:NULL];
[UIView setAnimationDuration:0.35];
[UIView setAnimationDelegate:self];
controller.view.center = CGPointMake(initialCenter.x, initialCenter.y);
//[UIView setAnimationDidStopSelector:#selector(aMethodToBeCalledAfterAnimationEnd:finished:context:)];
[UIView commitAnimations];
//[controller release];
}
You see I have a controller release as the last line in my add method. If I uncomment this line the animation completely dies and it just dumps the view into place with no animation.
Is there a better way to do release without having to create another method which does cleanup via [UIView setAnimationDidStopSelect:#selector(aMethodToBeCalledAfterAnmiationEnd... ?
Or can I do something like setAnimationDidStopSelector:#selector([controller release]) ? :)
Thanks in advance!
Using setAnimationDidStopSelector: is the proper way to solve the generic problem of releasing resources after an animation completes.
Take a step back and reconsider what you're doing here, though. Why are you looking to free the controller you just created? If you are only creating the controller for the purpose of getting at the view, that isn't the right way to do it. Build yourself a factory method to create your view, or use the methods in NSBundle to load the view from a NIB.
You can do this:
[UIView setAnimationDelegate: controller];
[UIView setAnimationDidStopSelector:#selector(release)];
I see you tagged this iphone-sdk-4.0. You could use the new block-based animations to do this and any other cleanup. See the documentation for details.

How to add an animation to the UIView in viewDidAppear?

I tried to add a animation to viewDidLoad and viewDidAppear, but it doesn't work:
- (void)viewDidAppear:(BOOL)animated{
[UIView beginAnimations:#"transition" context:NULL];
[UIView setAnimationTransition:110 forView:self.view cache:YES];
[UIView commitAnimations];
}
Why?
I had the same problem and I think I found the solution on this SO question.
When viewDidAppear gets called you still don't see anything on the screen (despite the name), but you are about to. You can then use a performSelector:withDelay or an NSTimer to launch your animation. The delay can just be 0.1 and your animation will play just when the screen appears.
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(#"View did appear!");
[self performSelector:#selector(animationCode) withObject:nil afterDelay:0.1f];
}
- (void)animationCode {
// you animation code
}
You are not telling the view which state it should animate to so it won't do anything. You need to place code between beginAnimations:context: and commitAnimations that changes the appearance of the view (e.g. by removing one subview and adding another).
You're not using beginAnimations: and commitAnimations correctly. You're supposed to put something in between them that normally wouldn't be animated: e.g. with self.view.alpha = 0.5 you get a fading effect. They have no effect on anything that isn't between them.
By the time viewDidAppear: is called, your view, well... has appeared. It's too late to animate anything. What you actually want to do is something like this:
- (void)showMyViewWithAnimation {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationTransition:110 forView:childView cache:YES];
[parentView addSubview:childView];
[UIView commitAnimations];
}
In the example above, childView is what in your example is called self.view.
Please write out the name of the transition; no one knows what 110 is by looking at it. It's bad style. </pedantry>