簡體   English   中英

如何使用貝塞爾曲線對對象進行動畫處理?

[英]How to animate object using bezier path?

在此處輸入圖片說明

這是我繪制虛線的代碼

func drawLine() {

    let shapeLayer = CAShapeLayer()
    shapeLayer.bounds = viewDraw.bounds
    shapeLayer.position = CGPoint(x: viewDraw.bounds.width/2, y: viewDraw.bounds.height/2)
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = ColorConstants.ThemeColor.cgColor
    shapeLayer.lineWidth = 3
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round // Updated in swift 4.2
    shapeLayer.lineDashPattern = [10]

    let path = UIBezierPath(roundedRect: viewDraw.bounds, cornerRadius: viewDraw.bounds.size.height/2)
    shapeLayer.path = path.cgPath

    viewDraw.layer.addSublayer(shapeLayer)

    let animation = CABasicAnimation(keyPath: "strokeEnd")
    animation.fromValue = 0
    animation.duration = 1
    shapeLayer.add(animation, forKey: "MyAnimation")
}

現在,按照我的屏幕截圖,我想在該無限長的時間內將藍點動畫化為紅點。 當藍點到達紅點時,它將再次以藍點開始。

注意:整個屏幕是動態的,因此,畫線也根據屏幕高度而動態

任何幫助,將不勝感激

你快到了

現在,您必須使用CAKeyframeAnimation添加動畫,該動畫具有屬性path ,您可以在其中傳遞要設置動畫的路徑

這是工作示例代碼

func drawLine() {

    let shapeLayer = CAShapeLayer()
    shapeLayer.bounds = self.view.bounds
    shapeLayer.position = CGPoint(x: self.view.bounds.width/2, y: self.view.bounds.height/2)
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = 3
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round // Updated in swift 4.2
    shapeLayer.lineDashPattern = [10]

    let path = UIBezierPath(roundedRect: self.view.bounds, cornerRadius: self.view.bounds.size.height/2)
    shapeLayer.path = path.cgPath

    self.view.layer.addSublayer(shapeLayer)

    let animation1 = CABasicAnimation(keyPath: "strokeEnd")
    animation1.fromValue = 0
    animation1.duration = 1
    shapeLayer.add(animation1, forKey: "MyAnimation")

    // Create  squareView and add animation 
    let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
    animation.duration = 1
    animation.repeatCount = MAXFLOAT
    animation.path = path.cgPath

    let squareView = UIView()

   // Don't worry about x,y and width and height it will not affect the animation 
    squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    squareView.backgroundColor = .lightGray
    view.addSubview(squareView)
    // You can also pass any unique string value for key
    squareView.layer.add(animation, forKey: nil)

}

您可以查看本教程以獲取更多幫助http://mathewsanders.com/animations-in-swift-part-two/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM