无法为Xamarin.iOS中的渐变图层设置动画效果

时间:2019-07-07 12:10:53

标签: c# ios xamarin xamarin.ios cabasicanimation

无法使用CABasicAnimation进行渐变图层动画设置。

CAGradientLayer gradientLayer = new CAGradientLayer();
gradientLayer.Colors = new CGColor[] { UIColor.Black.CGColor, UIColor.White.ColorWithAlpha(0.1F).CGColor, UIColor.Black.CGColor };
gradientLayer.StartPoint = new CGPoint(0, 0.5);
gradientLayer.EndPoint = new CGPoint(1.0, 0.525);
gradientLayer.Locations = new NSNumber[] { 0.4, 0.5, 0.6 };
gradientLayer.Frame = new CGRect(- shimmerView.Frame.Width, 0, 3 * shimmerView.Frame.Width, shimmerView.Frame.Height);

shimmerView.Layer.Mask = gradientLayer;

CABasicAnimation anmtn = new CABasicAnimation();
anmtn.KeyPath = "TransGrad";
anmtn.From = NSArray.FromObjects(new NSNumber[] { 0.0, 0.1, 0.2 });
anmtn.To = NSArray.FromObjects(new NSNumber[] { 0.8, 0.9, 1.0 });
anmtn.Duration = 2;
anmtn.RepeatCount = 1000;
gradientLayer.AddAnimation(animation, "loc");

我能够迅速使用相同的逻辑进行动画处理。请提供Xamarin.iOS的答案。

迅速

let light = UIColor.white.withAlphaComponent(0.1)
let dark = UIColor.black.cgColor
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [dark, light, dark]
gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.size.width, height: self.bounds.size.height)
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.525)
gradient.locations = [0.4, 0.5, 0.6]
self.layer.mask = gradient

let animation: CABasicAnimation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0.0, 0.1, 0.2]
animation.toValue = [0.8, 0.9, 1.0]

animation.duration = 1.5
animation.repeatCount = HUGE
gradient.add(animation, forKey: "shimmer")

1 个答案:

答案 0 :(得分:0)

问题似乎是您要为动画传递给KeyPath的值。 CAGradientLayer没有属性TransGrad,因此尝试使用该KeyPath添加动画将无效。

如果只是保持与Swift版本相同的关键路径,则动画应具有相同的行为:

CAGradientLayer gradientLayer = new CAGradientLayer();
gradientLayer.Colors = new CGColor[] { UIColor.Black.CGColor, UIColor.White.ColorWithAlpha(0.1F).CGColor, UIColor.Black.CGColor };
gradientLayer.StartPoint = new CGPoint(0, 0.5);
gradientLayer.EndPoint = new CGPoint(1.0, 0.525);
gradientLayer.Locations = new NSNumber[] { 0.4, 0.5, 0.6 };
gradientLayer.Frame = new CGRect(- shimmerView.Frame.Width, 0, 3 * shimmerView.Frame.Width, shimmerView.Frame.Height);

shimmerView.Layer.Mask = gradientLayer;

CABasicAnimation anmtn = new CABasicAnimation();
anmtn.KeyPath = "locations";
anmtn.From = NSArray.FromObjects(new NSNumber[] { 0.0, 0.1, 0.2 });
anmtn.To = NSArray.FromObjects(new NSNumber[] { 0.8, 0.9, 1.0 });
anmtn.Duration = 2;
anmtn.RepeatCount = 1000;
gradientLayer.AddAnimation(anmtn, "shimmer");

请注意,它是"locations"而不是"Locations",因为此值最终会传递给本机iOS库,因此大小写必须与该属性的命名方式匹配。

如果这不能解决您的问题,则需要提供有关C#代码中的shimmerView和Swift代码中的self以及这些代码段的上下文的更多信息。叫。