MichaelL
MichaelL

Reputation: 65

Using a slider to transition between 2 images

I am trying to learn the basics, but still very new to Xcode and Swift. I want to use a slider to transition between two images. When the slider is all the way to the left, image 1 should show in the image view. As the slider moves to the right, image 1 should fade and an image 2 should come into view. At the halfway point, both images should be visible (alpha = 0.5 for both image), superimposed one on top of the other. As the slider goes all the way to the right, image 1 should vanish and image 2 should be the only one visible.

Using UIImageView and a slider, I am able to adjust the alpha and "fade" my image based on the position of the slider.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBOutlet weak var UAimage: UIImageView!
    @IBOutlet weak var Slider: UISlider!

    @IBAction func sliderValueChange(_ sender: UISlider) {
        var currentValue = Float(sender.value)
        UAimage.alpha = CGFloat(sender.value)
    }

}

At this point, I am looking for help getting the second image added and using alpha to programmatically control its opacity.

Upvotes: 0

Views: 1081

Answers (2)

impression7vx
impression7vx

Reputation: 1863

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBOutlet weak var UAimage: UIImageView!
    /*
        Your 2nd image.
        On storyboard, go place a UIImageView directly on top of your initial imageView and set the image to whatever you'd like just as you did the original.
    */
    @IBOutlet weak var UAimage2: UIImageView! //Your 2nd image
    @IBOutlet weak var Slider: UISlider!

    @IBAction func sliderValueChange(_ sender: UISlider) {
        var currentValue = Float(sender.value)
        UAimage.alpha = CGFloat(sender.value)
        UAimag2.alpha = 1 - CGFloat(sender.value)
    }
}

Upvotes: 0

Chris
Chris

Reputation: 8091

Just add a 2nd imageview over the first and add this line imageview2.alpha = CGFloat(1 - sender.value)

Upvotes: 1

Related Questions