单击图像时如何在屏幕上随机移动UIimageView

时间:2018-06-13 19:28:56

标签: ios swift swift4 uiviewanimation uianimation

当我点击它时,你可以帮助我在我的视图上随机移动我的图像吗? 我需要使用UIView动画(需要),当UIImageView到达屏幕上的随机目的地时,它应该从内部改变颜色/图像。

这是我的代码:

import UIKit
import QuartzCore

// ---- Is required to use UIView Animation ------

class FirstViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.image = UIImage(named: "1.png") // the second image is named "2.png"

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
      guard let touch = touches.first else { return }

        let touchLocation = touch.location(in: view)
        let leftCorner = CGPoint(x: touchLocation.x + 48, y: touchLocation.y + 48)
        imageView.center = leftCorner
    }


}

提前致谢!

1 个答案:

答案 0 :(得分:1)

这是我的解决方案:

import UIKit

class ViewController: UIViewController {

    let imageViewWidth = CGFloat(100)
    let imageViewHeight = CGFloat(100)
    let colors = [UIColor.red, UIColor.blue, UIColor.gray, UIColor.brown, UIColor.green]

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.frame = CGRect(
            x: view.bounds.width/2 - imageViewWidth/2,
            y: view.bounds.height/2 - imageViewHeight/2,
            width: imageViewWidth,
            height: imageViewHeight
        )
        addTapRecognizerToImageView()
    }

    func addTapRecognizerToImageView() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
        imageView.addGestureRecognizer(tap)
        imageView.isUserInteractionEnabled = true
    }

    @objc func handleTap() {
        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
        UIView.animate(withDuration: 0.5) {
            self.imageView.frame = CGRect(
                x: CGFloat(randomX),
                y: CGFloat(randomY),
                width: self.imageViewWidth,
                height: self.imageViewHeight
            )
        }
        let randomColor = Int(arc4random_uniform(4) + 0)
        imageView.backgroundColor = colors[randomColor]
    }

}