【问题标题】:Animating CAShapelayer mask from Center of view [Swift]从视图中心动画 CAShapelayer 蒙版 [Swift]
【发布时间】:2020-12-09 21:55:45
【问题描述】:

我希望从视图中心为 CAShapelayer 设置动画。我的动画工作正常,但它是从 (0,0) 动画(扩展)而不是形状的中心。我在 ViewDidAppear 中调用它。这是我的代码:

    introAnimationImageView.image = UIImage(named:"mainBGblue")
    self.view.addSubview(introAnimationImageView)

    introAnimationImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    introAnimationImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
    introAnimationImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
    introAnimationImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
    introAnimationImageView.translatesAutoresizingMaskIntoConstraints = false
    
    let maskLayer = CAShapeLayer()
    maskLayer.frame = view.bounds
    // Create the frame for the circle.
    let radius: CGFloat = 10.0
    // Rectangle in which circle will be drawn
    let rect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 2 * radius, height: 2 * radius)
    let circlePath = UIBezierPath(ovalIn: rect)
    // Create a path
    let path = UIBezierPath(rect: view.bounds)
    // Append additional path which will create a circle
    path.append(circlePath)
    // Setup the fill rule to EvenOdd to properly mask the specified area and make a crater
    maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
    // Append the circle to the path so that it is subtracted.
    maskLayer.position = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    maskLayer.path = path.cgPath
    maskLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    
    // Mask our view with Blue background so that portion of red background is visible
    introAnimationImageView.layer.mask = maskLayer
    
    let layerAnimation = CABasicAnimation(keyPath: "transform.scale")
    layerAnimation.fromValue = 1
    layerAnimation.toValue = 50
    layerAnimation.isAdditive = false
    layerAnimation.duration = CFTimeInterval(1)
    layerAnimation.fillMode = .forwards
    layerAnimation.isRemovedOnCompletion = true
    layerAnimation.repeatCount = .infinity
    layerAnimation.autoreverses = true

    maskLayer.add(layerAnimation, forKey: "growingAnimation")

这是当前的输出(动画的静止图像):

如何从中心而不是向右下方(从 0,0)扩展 CAShapelayer?

【问题讨论】:

    标签: swift cashapelayer cabasicanimation


    【解决方案1】:

    根据this Obj-c thread找出答案

    改变:

    layerAnimation.toValue = 50 // Arbitrary number
    

    收件人:

    layerAnimation.toValue = NSValue(cgPoint: CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2))
    

    这给了我这个(动画的静止图像):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多