在Swift中实现平滑扩展UIView动画

3

目标:

如何使一个UIView动画效果展开并填充整个屏幕。在动画时,UIView需要平滑、均匀地扩展。

我有一个红色正方形,初始时很小,然后扩展到适合屏幕的大小。(图1)

let subview = UIView()
subview.backgroundColor = .red
subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
self.view.addSubview(subview)

Question:

In Swift 2 and Swift 3, using an animateWithDuration, how do I animate the the red square UIView expanding in a balanced and even manner in all directions to fill the whole screen?

UIView.animateWithDuration(1.0, delay: 0, options: nil, animations: {

    ?????

}, completion: nil)

图片 1:

在此输入图片描述


这是一张展示 IT 技术相关内容的图片。
2个回答

6
你可以尝试这个,我将持续时间设置为5秒,但你已经了解了思路。
let viewWidth = view.frame.width
let viewHeight = view.frame.height
UIView.animate(withDuration: 5) { 
    subview.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
}

这很简单。谢谢。 - user4806509

3

看起来你需要调整比例。

class ViewController: UIViewController {

var subview:UIView!

@IBOutlet weak var animateButton:UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    subview = UIView()
    subview.backgroundColor = .red
    subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
    self.view.addSubview(subview)

    self.view.bringSubview(toFront: animateButton)
}

@IBAction func animateButtonPressed(sender:UIButton) {
    if(sender.tag == 0) {

        let screenCenter = CGPoint(x:UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)
        let subviewCenter = self.view.convert(self.subview.center, to: self.view)
        let offset = UIOffset(horizontal: screenCenter.x-subviewCenter.x, vertical: screenCenter.y-subviewCenter.y)

        let widthScale = UIScreen.main.bounds.size.width/subview.frame.size.width
        let heightScale = UIScreen.main.bounds.size.height/subview.frame.size.height
        UIView.animate(withDuration: 1.0, animations: {
            let scaleTransform = CGAffineTransform(scaleX: widthScale, y: heightScale)
            let translateTransform = CGAffineTransform(translationX: offset.horizontal, y: offset.vertical)
            self.subview.transform = scaleTransform.concatenating(translateTransform)
        }, completion: { (finished) in
            sender.tag = 1;
        })

    } else {
        UIView.animate(withDuration: 1.0, animations: {
            self.subview.transform = CGAffineTransform.identity
        }, completion: { (finished) in
            sender.tag = 0;
        })
    }
}
}

enter image description here


1
谢谢您的建议。 - user4806509

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接