动画UIView时自动调整CAShapeLayer的大小

时间:2018-08-19 08:13:26

标签: ios swift

对不起,如果此问题已在其他地方得到解答。我尝试在多个地方搜索,但是找不到一个好的解决方案。我是Swift开发的初学者。

按照下面的代码,我正在创建一个SubView,向其添加一个椭圆形ShapeLayer,然后通过移动其中心并增大其大小来对SubView进行动画处理。

SubView正在正确设置动画,但是SubView内部的ShapeLayer并未更改大小。我希望“红色椭圆形”的大小增加,类似于SubView。如果能让我知道我的失踪,我将不胜感激。

class playGroundView: UIView {



override func draw(_ rect: CGRect) {
    // Add a blue rectangle as subview
    let startFrame = CGRect(x: self.frame.midX, y: self.frame.midY, width: 10, height: 20)
    self.addSubview(UIView(frame: startFrame))
    self.subviews[0].backgroundColor = UIColor.blue

    // Create red oval shape that is bounded by blue rectangle
    // Add red oval shape as sub-layer to blue rectangle view
    let subView = self.subviews[0]
    let ovalSymbol = UIBezierPath(ovalIn: subView.bounds)
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = ovalSymbol.cgPath
    shapeLayer.fillColor = UIColor.red.cgColor
    shapeLayer.strokeColor = UIColor.red.cgColor
    subView.layer.addSublayer(shapeLayer)

    // Animate movement and increase in size of blue rectangle view
    UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 3, delay: 0, options: [], animations: {
        let endFrame = CGRect(x:self.frame.midX - 50, y:self.frame.midY - 50, width: 20, height: 40)
        self.subviews[0].frame = endFrame
        self.setNeedsLayout()
        self.layoutIfNeeded()
    })

}
}

Image of Incorrect Output

1 个答案:

答案 0 :(得分:0)

好吧,在花更多的时间进行研究并更好地理解ViewController和UIView类中的内容之后,在这些类中输入以下内容对我来说是有效的:

内部类ViewController:UIViewController

override func viewDidLoad() {
    super.viewDidLoad()
    let startFrame = CGRect(x: playGround.frame.midX, y: playGround.frame.midY, width: 30, height: 60)
    cardSubView = cardView(frame: startFrame)
    playGround.addSubview(cardSubView!)

    let endFrame = CGRect(x: playGround.frame.midX - 100, y: playGround.frame.midY - 100, width: 60, height: 120)
    UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 10, delay: 0, options: [], animations: {
        self.cardSubView?.frame = endFrame
        self.cardSubView?.layoutIfNeeded()
    })
}

在UIView类中:

class cardView: UIView {

override func draw(_ rect: CGRect) {

    let backGroundPath = UIBezierPath(rect: rect)
    UIColor.blue.setFill()
    backGroundPath.fill()

    let ovalSymbol = UIBezierPath(ovalIn: rect)
    UIColor.red.setFill()
    ovalSymbol.fill()

}    

}

这仍然会导致iPhone模拟器中的动画结尾处出现怪异的帧阴影,但是在设备上运行时没有问题。