[英]How do I convert a CGColor into an NSObject when using Monotouch?
我正在尝试为 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");
}
但 animation 从不播放。 animationStarted 事件确实被引发了,所以大概它正在尝试运行 animation,但我在屏幕上看不到任何可见的证据。
我在一天的大部分时间里都在玩这个,我认为这是从 CGColor 到 NSObject 的转换——我试过 NSObject.FromObject、NSValue.ValueFromHandle 等,但还没有找到任何方法来获得animation 正确拾取开始和结束值。
为 animation 提供 CGColor 作为 NSObject 的正确方法是什么?
谢谢!
标记,
您可以使用
colorAnimation.To = Runtime.GetNSObject (UIColor.Blue.CGColor.Handle);
为 animation 获得正确的 object。
感谢 https://stackoverflow.com/users/187720/geoff-norton实际上给了我使用 Runtime.GetNSObject 的答案并解决了这个问题。
希望这可以帮助,
克里斯NTR
也可以这样做:
colorAnimation.From = NSObject.FromObject (UIColor.Red.CGColor.Handle);
MonoTouch 的下一个版本(6.0.8+)将允许:
colorAnimation.From = NSObject.FromObject (UIColor.Red.CGColor);
对于CGPath
和其他不是NSObject
的INativeObject
也是如此。
我刚刚查看了在我们的应用程序中编写的一些类似代码(诚然CAKeyFrameAnimation
而不是CABasicAnimation
),它们似乎已将.AddAnimation()
包装在 UIView animation 块中。 例如:
UIView.Animate(4, delegate{
shapeLayer.AddAnimation(colorAnimation, "animateColor");
});
我不确定这是否是正确的做法,但它似乎适用于我们的应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.