Animate Images in Uiimageview

Animate images in uiimageview

To download images from web service:

NSData *imageData = [NSData dataWithContentsOfURL:"*Url from web service*"];
UIImage *imageOne = [UIImage imageWithData:imageData];

likely download all images from web service and create an array like:

NSArray *imagesArray = [NSArray arrayWithObjects:imageOne...........,nil];

and use with little modification:

UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = imagesArray;
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];

How to animate the change of image in an UIImageView?

I am not sure if you can animate UIViews with fade effect as it seems all supported view transitions are defined in UIViewAnimationTransition enumeration. Fading effect can be achieved using CoreAnimation. Sample example for this approach:

#import <QuartzCore/QuartzCore.h>
...
imageView.image = [UIImage imageNamed:(i % 2) ? @"3.jpg" : @"4.jpg"];

CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;

[imageView.layer addAnimation:transition forKey:nil];

UIImageView transition between different images with animation

How can you do it?

you will need:

  1. A timer
  2. A counter
  3. An array of for holding image names

    var images:[String] = []

    var timer = Timer()

    var photoCount:Int = 0

in viewDidLoad i did this for initialization.

images = ["1","2","3"]
imageView.image = UIImage.init(named: "1")
timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(onTransition), userInfo: nil, repeats: true)

And the magic method for doing this is below:

func onTransition() {
if (photoCount < images.count - 1){
photoCount = photoCount + 1;
}else{
photoCount = 0;
}

UIView.transition(with: self.imageView, duration: 2.0, options: .transitionCrossDissolve, animations: {
self.imageView.image = UIImage.init(named: self.images[self.photoCount])
}, completion: nil)
}

Don't forget to pull your imageView referrence outlet. :)

   @IBOutlet weak var imageView: UIImageView!

How do I animate a set of UIImages backward inside UIImageVIew - swift - programmatically

I suggest we override the startAnimating() method. This way we can provide our own logic of the animation and decide what the next frame should be.

We'll create a frameTimer that will replace the image of the UIImageView every equal fraction of the animationDuration. It'll iterate over the images array forwards and backwards until stopped with the stopAnimating() method.

class BoomerangImageView: UIImageView {
// MARK: Overrides
override func startAnimating() {
guard let frames = animationImages, frames.count > 1 else {
return
}
image = frames.first

let timePerFrame = animationDuration / Double(frames.count)
let timer = Timer(fire: Date(timeIntervalSinceNow: timePerFrame),
interval: timePerFrame,
repeats: true) { [weak self] _ in
self?.changeFrame()
}
RunLoop.current.add(timer, forMode: .common)
frameTimer = timer
}

override func stopAnimating() {
frameTimer?.invalidate()
frameTimer = nil
currentFrameIndex = 0
}

// MARK: Private
private var frameTimer: Timer?
private var isAnimatingForward = true

private var currentFrameIndex = 0 {
didSet {
if let frames = animationImages,
currentFrameIndex >= 0,
currentFrameIndex < frames.count {
image = frames[currentFrameIndex]
}
}
}

private func changeFrame() {
guard let frames = animationImages, frames.count > 1 else {
stopAnimating()
return
}

let canAnimateForward = currentFrameIndex < frames.count - 1
let canAnimateBackward = currentFrameIndex > 0
isAnimatingForward = (isAnimatingForward && canAnimateForward) || (!isAnimatingForward && !canAnimateBackward)
currentFrameIndex += isAnimatingForward ? 1 : -1
}
}

Then in your view controller, you run the animation just like you planned:

class ViewController: UIViewController {
@IBOutlet weak var imageView: BoomerangImageView!

let frames: [UIImage] = [
// your images here
]

override func viewDidLoad() {
super.viewDidLoad()
imageView.animationImages = frames
imageView.animationDuration = 2
imageView.startAnimating()
}
}

It should look something like this:

boomerang demo

Swift - animating UIImageView image

You don't need to use CAffineTranform inside animateWithDuration, you can simply define the new center like:

let oldCenter = image.center
let newCenter = CGPoint(x: oldCenter.x - 100, y: oldCenter.y)

UIView.animate(withDuration: 1, delay: 0, options: .curveLinear, animations: {
image.center = newCenter
}) { (success: Bool) in
print("Done moving image")
}

Hope it helps.

How do I animate a UIImageView that was created programatically upon button click? (Each button click creates a new UIImageView with the same image)

You should not try to do a whole bunch of chained animations every 0.00001 seconds. Most things on iOS have a time resolution of ≈ .02 seconds.

You are trying to run an animation every 10 microseconds and move the image view 10 points each step. That comes to an animation of a million points per second. Don't do that.

Just create a single animation that moves the image view to it's final destination over your desired time-span. The system will take care of pacing the animation for you. (Say you move it 100 pixels in 0.3 seconds. Just specify a duration of 0.3 seconds, and the body of the animation moves the image view by 100 pixels. There you go. It will just work.

Note that your image views don't have any auto-layout constraints, so they will likely act strangely once the animation is complete.

How do I simultaneously animate a UIImageView's image and the UIImageView itself?

This is speculation and I haven't tested this idea at all, but have you considered implementing the image animation in the same fashion you're animating the position, with a CAKeyframeAnimation? You'd need to construct an array of CGImage objects from your UIImage array (to set the values property of the keyframe animation) but it looks like a pretty straightforward conversion:

CAKeyframeAnimation *imageAnimation = [CAKeyframeAnimation animation];
imageAnimation.calculationMode = kCAAnimationDiscrete; // or maybe kCAAnimationPaced
imageAnimation.duration = self.tileSet.constants.animationDuration;
imageAnimation.repeatCount = HUGE_VALF;
// the following method will need to be implemented to cast your UIImage array to CGImages
imageAnimation.values = [self animationCGImagesArray];
[self.playerSprite.layer addAnimation:imageAnimation forKey:@"contents"];

-(NSArray*)animationCGImagesArray {
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self.player.animationImages count]];
for (UIImage *image in self.player.animationImages) {
[array addObject:(id)[image CGImage]];
}
return [NSArray arrayWithArray:array];
}


Related Topics



Leave a reply



Submit