D
D
Denis2018-07-11 21:41:03
Animation
Denis, 2018-07-11 21:41:03

How to make animation for UIImageView?

There is a simple code - when you press a button, an image of an eagle or tails appears.

@IBAction func buttonCoin(_ sender: UIButton) {
        let coinSide = arc4random_uniform(2)
        if coinSide == 0 {
            labelResult.text = "Tail"
            imageCoin.image = UIImage(named: "tail")

        }else{
            labelResult.text = "Head"
            imageCoin.image = UIImage(named: "head")
        }
     
    }

1. How to make an animation so that when the button is pressed, the image appears (for example, it stretches from a reduced to full size or becomes visible from a transparent one)
2. How to make an animation so that when the button is pressed, the images change several times imitating a flip of a coin, and then the result would appear

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2018-07-23
@foma24

1.

imageView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)

UIView.animate(withDuration: 0.6,
    animations: { [weak self] in
        self?.imageView.transform = .identity
    })

imageView.alpha = 0.0

UIView.animate(withDuration: 0.6,
    animations: { [weak self] in
        self?.imageView.alpha = 1.0
    })

2. The function to rotate the UIImageView, Outlet will be called 'imageBackground' in this example.
private let animationRepeatDuration: CFTimeInterval = 2.0
private let rotationAnimatonKey: String = "rotationAnimation"

func animate(completion: @escaping () -> Void) {
        
        CATransaction.begin()
        
        CATransaction.setCompletionBlock { [weak self] in
            
            guard
                let rotationAnimatonKey = self?.rotationAnimatonKey,
                self?.imageBackground.layer.animation(forKey: rotationAnimatonKey) != nil
                else {
                completion()
                return
            }
        }
        
        let rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.y")
        rotation.toValue = NSNumber(value: Double.pi * 2)
        rotation.repeatCount = Float.greatestFiniteMagnitude
        rotation.repeatDuration = animationRepeatDuration
        imageBackground.layer.add(rotation, forKey: rotationAnimatonKey)
        
        CATransaction.commit()
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question