如何在动画期间获取 UIImage 的当前大小

How To Get the Current Size of a UIImage During Animation

我有一张图像 (innerCircle),它使用以下动画按比例增大和缩小:

UIView.animateWithDuration(5, delay:0, options: [.Repeat, .Autoreverse], animations: { () -> Void in
        self.innerCircle.transform = CGAffineTransformMakeScale(3.5, 3.5)
    }) { (finished: Bool) -> Void in
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.innerCircle.transform = CGAffineTransformIdentity

我试图在动画期间的任何时间点获取图像的 当前 大小,以便我可以检查它何时超过某个点。我想这样做,这样我就可以将文本标签从 "Inhale" 更改为 "Exhale",反之亦然。

我试过使用

let innerCircleWidth = self.innerCircle.image!.size.width

但这只能获取初始宽度值。它不会更新。

非常感谢!

那是因为图片的大小没有改变。应用变换不会更改视图的大小。

当使用 UIView.animateWithDuration 获取有关当前显示内容的准确信息时,您应该检查动画视图的 presentationLayer,在您的情况下 innerCircle.layer.presentationLayer()?.frame 而不是视图的框架本身。有关此的更多信息,请参阅 here.

要了解其工作原理,您可以将以下代码放在 swift 游乐场中。

import UIKit
import XCPlayground

let outerCircle = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 1000))
let innerCircle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100, height: 100))
outerCircle.addSubview(innerCircle)
innerCircle.center = outerCircle.center
innerCircle.backgroundColor = UIColor.redColor()
UIView.animateWithDuration(5, delay:0, options: [.Repeat, .Autoreverse], animations: { () -> Void in
    innerCircle.transform = CGAffineTransformMakeScale(3.5, 3.5)
}) { (finished: Bool) -> Void in
    UIView.animateWithDuration(1, animations: { () -> Void in
        innerCircle.transform = CGAffineTransformIdentity
    })
}



class TimerObject: NSObject {
    override init()
    {
        super.init()
        let timer = NSTimer(timeInterval: 0.10, target: self, selector: #selector(self.printPresentationFrame), userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
    }

    @objc func printPresentationFrame()
    {
        print(innerCircle.layer.presentationLayer()?.frame)
    }
}
let timerObject = TimerObject()

XCPlaygroundPage.currentPage.liveView = outerCircle