これは私が昨日尋ねた質問に追加されたものです。結果は完璧でしたが、修正が必要です。 Using drawRect to draw & animate two graphs. A background graph, and a foreground graphCAShapeLayer/CAGradientLayerのアニメーション
次のコードは、上記のスレッドに基づいて、濃い青の「三角形」を拡大するCABasicAnimationを生成します。暗い青の単色ではなく、赤/緑/青の3つのストップを持つCAGradientLayerにしたいと思います。
グラデーションを設定するためにCAGradientLayerを追加してから、addSubLayerを使用してアニメーション化するCAShapeLayerにグラデーションを追加しようとしました。私が下に投稿している結果はアニメートされません。色と形は静的なままです。勾配が偉大に見える、それが出てアニメーション化するためにちょうど必要があります。
import UIKit
import QuartzCore
import XCPlayground
let view = UIView(frame: CGRect(x: 0, y: 0, width: 521, height: 40))
view.backgroundColor = UIColor.whiteColor()
XCPlaygroundPage.currentPage.liveView = view
let maskPath = UIBezierPath()
maskPath.moveToPoint(CGPoint(x: 0, y: 30))
maskPath.addLineToPoint(CGPoint(x: 0, y: 25))
maskPath.addLineToPoint(CGPoint(x: 300, y: 10))
maskPath.addLineToPoint(CGPoint(x: 300, y: 30))
maskPath.closePath()
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
maskLayer.fillColor = UIColor.whiteColor().CGColor
let rectToAnimateFrom = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 0, height: 40))
let rectToAnimateTo = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 97, height: 40))
let backgroundGray = CAShapeLayer()
backgroundGray.path = maskPath.CGPath
backgroundGray.fillColor = UIColor.grayColor().CGColor
let foregroundGradient = CAShapeLayer()
foregroundGradient.mask = maskLayer
foregroundGradient.backgroundColor = UIColor.clearColor().CGColor
let gradientLayer = CAGradientLayer()
gradientLayer.startPoint = CGPointMake(0, 0)
gradientLayer.endPoint = CGPointMake(1, 0)
gradientLayer.frame = maskPath.bounds
let colors = [UIColor.redColor().CGColor, UIColor.greenColor().CGColor, UIColor.blueColor().CGColor]
gradientLayer.colors = colors
foregroundGradient.addSublayer(gradientLayer)
view.layer.addSublayer(backgroundGray)
view.layer.addSublayer(foregroundGradient)
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = rectToAnimateFrom.CGPath
animation.toValue = rectToAnimateTo.CGPath
animation.duration = 2
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
foregroundGradient.addAnimation(animation, forKey: nil)
私は左から右にアニメーション化するために(!gradientLayerサブレイヤと)foregroundGradientオブジェクトが必要です。
上記のコードからグラデーションを削除し、foregroundGradientを単色で保存すると、アニメーションが表示されます。
あなたがここで直面している問題を教えてください。 – CodeChanger
@Dhanesh - 第3段落に記載されています。グラデーションは完璧に完璧です。私が必要とする正確なサイズと色。しかし、アニメーションは機能しません。私が投稿したスレッドを見てください。青は左から右に、灰色の三角は背景です。グラデーションを使用する以外は同じ結果が必要です。 – Joe