如何随机移动(翻译)图片,屏幕的任何位置?

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

我想将图像翻译到屏幕上的任何位置?我应该怎么办?

我想做一个项目,用户要求将图像放在屏幕的任意位置,3 秒后应移动到任意位置,现在用户更改了在屏幕上随机动画图片的要求。

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)
    }

图片应该是随机翻译的,其实我想让这张图片在屏幕上随机移动。

所以你必须使用UIView.animate。您可以更改动画持续时间。

例如

      var imageView: UIImageView!

      override func viewDidLoad() {
            super.viewDidLoad()
            imageView = UIImageView(frame: CGRect(x: CGFloat(randomX), y: CGFloat(randomY), width: 200, height: 200))
            imageView.image = UIImage(named: "loading")
            imageView.contentMode = .scaleAspectFit
            self.view.addSubview(imageView)
            SchedulingMethod()
    }


  @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

        UIView.animate(withDuration: 0.4) {
                self.imageView.frame.origin.x = randomX;
                self.imageView.frame.origin.y = randomY;
            }
    }

我个人认为 CGAffineTransform 是正确的选择。

@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)
    }
}

如果您需要对图像视图执行任何其他转换,这将为您提供很好的灵活性。

查看:Hacking with Swifts教程