Search code examples
iosswiftrandomimageviewmotion

How can I move(translate) picture randomly, any position of the screen?


I want to translate image to any position in the screen? what should I do?

I want to make a project, where user asked to put an image anywhere in the screen and that should move to any place after 3 seconds, now user changed the requirement to animate picture randomly on the screen.

class ViewController: UIViewController {
    var timer = Timer()
    var imageView: UIImageView!
    let imageViewWidth = CGFloat(100)
    let imageViewHeight = CGFloat(100)



    override func viewDidLoad() {
        super.viewDidLoad()

        SchedulingMethod()

    }

    func SchedulingMethod() {
        timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(updatePosition), userInfo: nil, repeats: true)
    }
    @objc func updatePosition() {

        let maxX = view.frame.maxX-imageViewWidth
        let maxY = view.frame.maxY-imageViewHeight
        let randomX = arc4random_uniform(UInt32(maxX)) + 0
        let randomY = arc4random_uniform(UInt32(maxY)) + 0

        print("chutiyaap")
        imageView = UIImageView(frame: CGRect(x: CGFloat(randomX), y: CGFloat(randomY), width: 200, height: 200))
        imageView.image = UIImage(named: "loading")
        imageView.contentMode = .scaleAspectFit
        for view in self.view.subviews {
            view.removeFromSuperview()
        }

        self.view.addSubview(imageView)
    }

picture should translate randomly, actually I want this image to move randomly on the screen.


Solution

  • Personally I think CGAffineTransform is the way to go.

    @objc func updatePosition() {
        let maxX = view.frame.maxX - imageViewWidth
        let maxY = view.frame.maxY - imageViewHeight
        let xCoord = CGFloat.random(in: 0...maxX)
        let yCoord = CGFloat.random(in: 0...maxY)
    
        UIView.animate(withDuration: 0.3) {
            imageView.transform = CGAffineTransform(translationX: xCoord, y: yCoord)
        }
    }
    

    This will give you good flexibility if you need to perform any other transformations to the image view.

    Check out: Hacking with Swifts tutorial