【问题标题】:How to animate UIBezierPath inside of draw(_:)?如何在 draw(_:) 中为 UIBezierPath 设置动画?
【发布时间】:2020-04-28 13:08:45
【问题描述】:

我的任务是在draw(_:) 方法中绘制矩形并为其高度设置动画。

var height = 0
override func draw(_ rect: CGRect) {
    let rect = CGRect(x: 0, y: 0, width: 100, height: height)
    let rectanglePath = UIBezierPath(rect: rect)
    UIColor.green.setFill()
    rectanglePath.fill()
}

我正在寻找这样的动画:

func animate() {
    UIView.animate(withDuration: 2) {
        self.height = 300
    }
}

我也可以使用CAShapeLayerCABasicAnimation,但是我不知道如何在draw(_:)方法中绘制它。此任务需要使用draw(_:) 方法:(

【问题讨论】:

  • 什么意思“在这个任务中需要使用draw(_:)方法”?当操作系统告诉您它需要更新时,您覆盖 draw(_:) 以更新矩形...
  • 正确。 “必需”意味着我必须在此任务中使用此方法。我知道还有其他方法可以解决它,但我让你使用方法 draw(_:)
  • 嗯,这就像说 “我必须在用户输入任何文本之前评估输入到字段中的文本。” 仅仅因为您认为您必须在特定的功能并不意味着它是正确的地方。也许如果您编辑您的问题并准确解释您想要做什么以及为什么您认为必须在draw(_:) 中完成?

标签: ios swift uibezierpath caanimation


【解决方案1】:
class View: UIView{
override func draw(_ rect: CGRect)
{
    let rectanglePath = UIBezierPath(rect: self.frame)
    UIColor.green.setFill()
    rectanglePath.fill()
}}
class ViewController: UIViewController{

override func viewDidLoad()
{
    super.viewDidLoad()
    let subview = View(frame:  CGRect(x: 0, y: 0, width: 100, height: 0))
    self.view.addSubview(subview)

    UIViewPropertyAnimator.runningPropertyAnimator(
       withDuration: 2,
       delay: 0,
       options: .curveLinear,
       animations: {self.view.subviews[0].frame = CGRect(x: 0, y: 0, width: 100, height: 100)}
    )

}}

【讨论】:

  • 感谢您的回答,但它不会为路径设置动画。框架不是我可以用于动画的
  • 不客气。唯一可以设置动画的 UIView 属性是 frame、bounds、center、transform、alpha、backgroundColor:developer.apple.com/documentation/uikit/uiview
猜你喜欢
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多