I have a few buttons I would like to animate.
I have looked at and tried the animateWithDuration method but that seems to be for Views and I couldnt get my implementation to work.
Can this method work for animating buttons too? if not how could it be done?
EDIT
I have the following code
-(void) animate:(UIButton*) b withMonster: (int) monster withState: (int) state andLastState:(int) last_state {
if (state < last_state) {
float duration = 1.0 / 10;
__block int stateTemp = state;
[b animateWithDuration: duration
animations: ^{ [UIImage imageNamed:[NSString stringWithFormat:#"m%d.a000%d.png", monster, state]]; }
completion: ^{ [self animate: A1 withMonster: monster withState: stateTemp++ andLastState: last_state];; }];
}
and I call it like so
[self animate: A1 withMonster: monsterDecider withState: 1 andLastState: 5];
When this code executes the app crashes.
Is it correct to call is with self in both calls(self being ViewController).
Thanks
You can animate buttons, yes. In the animations block you need to change some of the button parameters like this:
[UIView animateWithDuration:animTime
animations:^{button.frame = newFrame;}];
Looking at your code you probably want to set the button.imageView.image property to a new image (your code currently loads a new image but doesn't set it onto the button).
However, UIImageView objects actually support changing between multiple images without needing to use the UIView animateWithduration:... methods.
You probably want to set the following properties:
button.imageView.animationImages
button.imageView.animationDuration
button.imageView.animationRepeatCount
Then call
[button.imageView startAnimating];
and the UIImageView will do all the animation for you.
See the docs on UIImageView:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImageView_Class/Reference/Reference.html
Related
I've made a program that generates an image at a random x-coordinate at the top of the screen. The image then falls down to the bottom. However, I want to keep generating new images (of the same image) every few seconds so that it's as though these duplicates of the same image are continually "raining" from the top. (Note: Eventually, as I continue to develop this app, I will need to recall the location of each image at any moment, so I believe I will need each spawned image to be part of an array. I also believe I must move each image step-by-step, so I cannot rely on animation).
The problem is: How can I make all of this code repeat every 0.5 seconds so that each newly spawned image has its own moveObject timer. It will be like raindrops falling from the top.
#implementation ViewController {
UIImageView *_myImage;
}
- (void)viewDidLoad
{
srand(time(NULL));e
int random_x_coordinate = rand() % 286;
CGRect myImageRect = CGRectMake(random_x_coordinate, 0.0f, 40.0f, 40.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:#"flake.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
_myImage = myImage;
//FALLING BIRDS TIMER
moveObjectTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:#selector(moveObject) userInfo:nil repeats:YES];
}
//FALLING BIRDS MOVER
-(void) moveObject { // + means down and the number next to it is how many pixels y moves down per each tick of the TIMER above
_myImage.center = CGPointMake(_myImage.center.x, _myImage.center.y +1);
}
You have different solutions:
Just 1 timer in which you update an array of UIImageView (I prefer this one)
Subclass Imageview and put the timer inside the class so each one would have its own timer
Maybe you can use [UIView animateWithDuration... instead of timers, but not sure if you can use many at the same time.
The problem is: How can I make all of this code repeat every 0.5
seconds so that each newly spawned image has its own moveObject timer.
Look into Core Animation's particle effects -- they're not just for smoke, fog, and fire. By setting up a particle emitter and creating particle cells using your image, you can have Core Animation take care of the whole operation. I don't see much official documentation on the topic, but you can read the reference page for CAEmitterLayer to get an idea of how it works, and then take a look at the tutorial on raywenderlich.com.
Use this function for each raindrop object.Just provide point to move to:
-(void)raindropAnimation:(CGPoint)dropPoint
{
raindrop.frame = CGRectMake(dropPoint.x,0,raindrop.frame.size.width,raindrop.frame.size.height) //here y is 0 ie topmost
[UIView animateWithDuration:2.0
delay:0.0
options:UIViewAnimationCurveEaseInOut
animations:^ {
raindrop.frame = CGRectMake(dropPoint.x,dropPoint.y,raindrop.frame.size.width,raindrop.frame.size.height) //will move to point
}
completion:^(BOOL finished) {
[self perfromSelector:#selector(raindropAnimation:CGPointMake(xnewpointhere,ynewpointhere))];
}];
I have made a subclass of UIView and i'm trying to animate a property in that subclass.
The property is used in drawRect and I want drawRect to execute at each step of the animation.
So I made it the property setter like this:
-(void) setFill:(float) f
{
fill = f;
[self setNeedsDisplay];
}
But when I run the animation block the property get set right away. What am I doing wrong?
Animation call looks like this:
[UIView animateWithDuration:3.0f
delay:0.0f
options: UIViewAnimationOptionCurveLinear
animations: ^{ circle1.fill = 50; }
completion: ^(BOOL finished) { }];
Is this the right way to go animating your UIView subclasses?
Only certain properties of UIView are animatable (frame, center, transform...). You have to write your own animation to animate your custom properties using NSTimer.
In my iPad app I have a view controller with a small table view. When you tap on the table view it opens a modal view controller that is a larger and more refined version of the small table view. I would like to create an animation from a pre-rendered image of the large view controller by scaling the image down to be the size of the small table view and zoom it to full screen size and then replace the image with the "real" view controller.
Something like:
LargeViewController* lvc = [[LargeViewController alloc] init];
[self presentModalViewController:lvc byZoomingFromRect:CGRectMake(50,50,200,300)];
I know you can produce an image from a view:
- (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
But how do I make the view controller draw itself (offscreen) so I can take it's view and scale the image in an animation to fill screen?
Thanks in advance.
I suppose you want to create your very own animation. Last month I played around with something like that. My solution was adding a custom view (maybe taken from a view controller) to the current view as an overlay. This works with layers, too.
First you fetch the Image from your "future" or "present" view controller, like you did in your code example above. Normally the view controllers content should be available while rendering to the context.
Now you have the image. The manipulation of the image must be done by you.
Add the image to a UIImageView. This ImageView can be added as subview or layer. Now you have a layer where you can freely draw above your actual user interface. Sometimes you have to move the layer or view around, so that it perfectly overlays your view. This depends on your view setup. If you are dealing with Tableviews, adding a subview is not that easy. So better use the layer.
After all the work was done, present the new view controller without animation, so that it appears immediately.
Remove the layer or view from your parent view after the work was done, and clean up.
This sounds complicated, but once you've done that you have a template for that. In "WWDC 2011, Session 309 Introducing Interface Builder Storyboarding" apple introduced 'custom segues', where you'll find a mechanism for exactly what you want to do. The code below is a cut out of an older project and is somehow messy and must be cleaned up. But for showing the principle this should work:
-(void) animate {
static LargeViewController* lvc = [[LargeViewController alloc] init];
UIGraphicsBeginImageContextWithOptions(self.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
[lvc.view.layer renderInContext:UIGraphicsGetCurrentContext()];
// Create a ImageView to display your "zoomed" image
static UIImageView* displayView = [[UIImageView alloc] initWithFrame:self.view.frame];
static UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Add your image to the view
displayView.image = img;
// insert the view above your actual view, adjust coordinates in the
// frame property of displayView if overlay is misaligned
[[self.view] addSubview:displayView];
// alternatively you can use the layer
// [self.view.layer addSublayer:displayView.layer];
// draw the imageView
[displayView setNeedsDisplay];
// do something in background. You may create your own
// construction, i.e. using a timer
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDate *now = [NSDate date];
NSTimeInterval animationDuration = 3.;
NSTimeInterval t = -[now timeIntervalSinceNow];
while (t < animationDuration) {
t = -[now timeIntervalSinceNow];
// Do some animation here, by manipulation the image
// or the displayView
// <calculate animation>, do something with img
// you have exact timing information in t,
// so you can set the scalefactor derived from t
// You must not use an UIImage view. You can create your own view
// and do sth. in draw rect. Do whatever you want,
// the results will appear
// in the view if you added a subview
// or in a layer if you are using the layer
dispatch_sync(dispatch_get_main_queue(), ^{
// display the result
displayView.image = img;
[displayView setNeedsDisplay];
});
}
});
// now the animation is done, present the real view controller
[self presentModalViewController:lvc animated:NO];
// and clean up here
}
Perhaps you could use something like
CGAffineTransform tr = CGAffineTransformScale(lvc.view.transform, 0.5, 0.5);
to embed a scaled down version of the view in your parent view controller, then present lvc modally and restore scale when the user taps the view.
UIKit takes care of most of this for you. While jbat100's solution could be made to work too, you should be able to do this simply by setting lvc's initial frame to the smaller rect you want to start out at and then when you set the frame too its full size, the implicit animation for changing the frame will handle the zooming animation for you. Each UIView has a CALayer that its content is drawn in and that layer has several implicit animtions setup to animated changes to certain properties such as the frame or position properties. Here is my untested stab at it:
.
.
lvc.view.frame = CGRectMake(50,50,200,300);
[self performSelector:#selector(setFrameToFullScreen) withObject:nil afterDelay:0];
}
- (void)setFrameToFullScreen {
lcv.view.frame = [UIScreen mainScreen].bounds;
}
The performSelector:withObject:afterDelay call will cause setFrameToFullScreen to be called on the next run loop cycle. If you don't do something like that, then only the final frame will be used and the system won't recognize the change in the frame and apply its implicit animation to the views layer.
I have an animation using a UIImageView:
myAnimatedView.animationImages = myImages;
myAnimatedView.animationDuration = 1;
myAnimatedView.animationRepeatCount = 1;
[myAnimatedView startAnimating];
How can I tell to animation to stop at the last frame (keeping the last image in the series visible)?
the image property on the UIImageView class has the following docs:
"If the animationImages property contains a value other than nil, the contents of this property are not used."
So the trick to hold on the last frame of an animation in iOS4 is to first set the image property to that last frame (while animationImages is still nil), then set the animationImages property and call startAnimating. When the animation completes, the image property is then displayed. No callback/delegate needed.
You can set image of last frame to your UIImageView instance and then when animation will finish last frame image remains visible. Here is the code:
// create your array of images
NSArray *images = #[[UIImage imageNamed:#"video1.png"], [UIImage imageNamed:#"video2.png"]];
UIImageView *imageView = [UIImageView new];
imageView.image = images.lastObject;
imageView.animationImages = images;
imageView.animationDuration = 1.0; // seconds
imageView.animationRepeatCount = 1;
[imageView startAnimating];
After the animation finishes you can set your UIImageView image to the last frame of your animation.
myAnimatedView.image = [myAnimatedImages objectAtIndex:myAnimatedImages.count - 1]
I don't think there is a delegate method that would notify you on animationFinish event so you would need to start a NSTimer with same duration as the animation to get the notification.
UIImageViewAnimation documentation
Swift version will be as given below but in objective-c logic will be same
you can hack it just setting the image of the UIImageView to the last image of the images array. just before the code of animation, like imageView.image = arrayOfImage.last
the whole logic is given below
imageView.image = arrayOfImage.last //(this line create magic)
imageView.animationImages = arrayOfImage
imageView.animationDuration = 1.0
imageView.animationRepeatCount = 1
imageView.startAnimating()
I just toss a UIView holding the first frame on top of the animation UIView...
make the animation view hidden and set it's image as the last frame...
and then have them switch hidden properties during the process.
so... just before your last line...
// quickly hide the view that only holds the first frame
myOtherView.hidden = YES;
// start the animation
[myAnimatedView startAnimating];
// show the animation view
myAnimatedView.hidden = NO;
// BAM, done. It will use the last image when it ends.
Less code, more IB, whenever possible.
I've achieved this by creating a subclass of UIImageView, overriding startAnimating() and setting the image property to be the last image in your image array before you call super.startAnimating().
This in addition to setting the animationRepeatCount to 1 achieves the desired effect.
Here is my Swift class:
class SuccessAnimationImageView: UIImageView {
var duration: NSTimeInterval = 2
override func didMoveToSuperview() {
super.didMoveToSuperview()
setupImages()
}
override func startAnimating() {
setLastFrame()
super.startAnimating()
}
func setupImages() {
animationImages = ImageHelper.successAnimationImages
image = animationImages?.first
animationRepeatCount = 1
}
func setLastFrame() {
image = animationImages?.last
}
}
Was having issues in start/stop animation & managing animation count So used this pod
imageViewObject.animate(withGIFNamed: "gif_name", loopCount: 1) {
print("animating image")
}
To start/stop animation :
imageViewObject.isAnimatingGIF ? imageViewObject.stopAnimatingGIF() : imageViewObject.startAnimatingGIF()
Have you set the removedOnCompletion property of the rotation animation to NO,
e.g.,
rota.removedOnCompletion = NO;
That should leave the presentation layer where it was when the animation finished. The default is YES, which will snap back to the model value, i.e., the behavior you describe.
The fillMode should also be set,
i.e.,
rota.fillMode = kCAFillModeForwards;
You can Stop the animation by setting the UIImageView property
animateImg.animationDuration = 1
I am trying to rotate my object like shakes dice.
please suggest simplest way to implement it in my iphone application.
Any kind of sample code or documentation.
http://www.amazon.com/OpenGL-SuperBible-Comprehensive-Tutorial-Reference/dp/0321498828
If you want to do this without using OpenGL you can use a UIImageView and the set a series of animation images. By creating a series of images you can create a "rolling dice" effect. Here is an example of how to do this:
// create a UIImageView
UIImageView *rollDiceImageMainTemp = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rollDiceAnimationImage1.png"]];
// position and size the UIImageView
rollDiceImageMainTemp.frame = CGRectMake(0, 0, 100, 100);
// create an array of images that will represent your animation (in this case the array contains 2 images but you will want more)
NSArray *savingHighScoreAnimationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"rollDiceAnimationImage1.png"],
[UIImage imageNamed:#"rollDiceAnimationImage2.png"],
nil];
// set the new UIImageView to a property in your view controller
self.viewController.rollDiceImage = rollDiceImageMainTemp;
// release the UIImageView that you created with alloc and init to avoid memory leak
[rollDiceImageMainTemp release];
// set the animation images and duration, and repeat count on your UIImageView
[self.viewController.rollDiceImageMain setAnimationImages:savingHighScoreAnimationImages];
[self.viewController.rollDiceImageMain setAnimationDuration:2.0];
[self.viewController.rollDiceImageMain.animationRepeatCount:3];
// start the animation
[self.viewController.rollDiceImageMain startAnimating];
// show the new UIImageView
[self.viewController.view addSubview:self.rollDiceImageMain];
You can modify the creation and setup including the size, position, number of images, the duration, repeat count, etc as needed. I've used this feature of UIImageView to create simple animation effects and it works great!
Please let me know if you try this and if it works for your needs. Also, post any follow up questions.
Bart
nice your example, but do you think it's possible to rotate / control the rotation with touch gesture ?