我正在尝试为 CAShapeLayer 上的 CGColor fillColor 属性设置动画。我可以使用具有以下语法的 Objective-C 使其正常工作:
- (void)viewDidLoad {
[super viewDidLoad];
// Create the path
thisPath = CGPathCreateMutable();
CGPathMoveToPoint(thisPath, NULL, 100.0f, 50.0f);
CGPathAddLineToPoint(thisPath, NULL, 10.0f, 140.0f);
CGPathAddLineToPoint(thisPath, NULL, 180.0f, 140.0f);
CGPathCloseSubpath(thisPath);
// Create shape layer
shapeLayer = [CAShapeLayer layer];
shapeLayer.frame = self.view.bounds;
shapeLayer.path = thisPath;
shapeLayer.fillColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:shapeLayer];
// Add the animation
CABasicAnimation* colorAnimation = [CABasicAnimation animationWithKeyPath:@"fillColor"];
colorAnimation.duration = 4.0;
colorAnimation.repeatCount = 1e100f;
colorAnimation.autoreverses = YES;
colorAnimation.fromValue = (id) [UIColor redColor].CGColor;
colorAnimation.toValue = (id) [UIColor blueColor].CGColor;
[shapeLayer addAnimation:colorAnimation forKey:@"animateColor"];
}
这会按预期设置颜色变化的动画。当我将它移植到 Monotouch 时,我尝试了:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
thisPath = new CGPath();
thisPath.MoveToPoint(100,50);
thisPath.AddLineToPoint(10,140);
thisPath.AddLineToPoint(180,140);
thisPath.CloseSubpath();
shapeLayer = new CAShapeLayer();
shapeLayer.Path = thisPath;
shapeLayer.FillColor = UIColor.Red.CGColor;
View.Layer.AddSublayer(shapeLayer);
CABasicAnimation colorAnimation = CABasicAnimation.FromKeyPath("fillColor");
colorAnimation.Duration = 4;
colorAnimation.RepeatCount = float.PositiveInfinity;
colorAnimation.AutoReverses = true;
colorAnimation.From = NSObject.FromObject(UIColor.Red.CGColor);
colorAnimation.To = NSObject.FromObject(UIColor.Blue.CGColor);
shapeLayer.AddAnimation(colorAnimation, "animateColor");
}
但动画永远不会播放。animationStarted 事件确实被引发了,所以大概它正在尝试运行动画,但我在屏幕上看不到任何可见的证据。
我在一天的大部分时间里都在玩这个,我认为这是从 CGColor 到 NSObject 的转换——我试过 NSObject.FromObject、NSValue.ValueFromHandle 等,但还没有找到任何方法来获得正确拾取开始和结束值的动画。
为动画提供 CGColor 作为 NSObject 的正确方法是什么?
谢谢!