我試圖在更改自定義屬性時觸發CALayer的動畫。當我改變我的圓的半徑時,我希望圖層自動觸發它的動畫。在Objective-C中,通過將@dynamic
屬性設置爲屬性並覆蓋actionForKey:
方法,可以設置動畫(like in this example)。更改自定義屬性時動畫CALayer
public class MyCircle : CALayer
{
[Export ("radius")]
public float Radius { get; set; }
public MyCircle()
{
Radius = 200;
SetNeedsDisplay();
}
[Export ("initWithLayer:")]
public MyCircle (CALayer other) : base (other)
{ }
public override void Clone (CALayer other)
{
base.Clone (other);
MyCircle o = other as MyCircle;
Radius = o.Radius;
}
public CABasicAnimation MakeAnimationForKey (String key)
{
CABasicAnimation animation = CABasicAnimation.FromKeyPath (key);
animation.From = PresentationLayer.ValueForKey (new NSString (key));
animation.Duration = 1;
return animation;
}
[Export ("actionForKey:")]
public override NSObject ActionForKey (string key)
{
switch (key.ToString())
{
case "radius":
return MakeAnimationForKey (key);
default:
return base.ActionForKey (key);
}
}
[Export ("needsDisplayForKey:")]
static bool NeedsDisplayForKey (NSString key)
{
switch (key.ToString())
{
case "radius":
return true;
default:
return CALayer.NeedsDisplayForKey (key);
}
}
public override void DrawInContext (CGContext ctx)
{
// draw circle based in radius
}
}
然而,在我的C#/ MonoTouch的代碼, 「半徑」 是從來沒有當值改變發送到ActionForKey。在上一個問題(Animate a custom property using CoreAnimation in Monotouch?)中,答案和提供的示例代碼基於手動調用的自定義屬性動畫(我不需要)。
Monotouch是否支持我所期望的行爲?我究竟做錯了什麼?
究竟你是什麼意思「該自定義屬性動畫被手動調用「爲另一個答案中的示例代碼? –
在GitHub上的示例代碼中,您可以在AppDelegate/FinishedLaunching中明確設置所有動畫。但是在我鏈接的Objective-C代碼中,當CALayer子類中的屬性發生更改時,將調用ActionForKey。後者是一個整潔的,因爲CALayer子類本身負責轉換(而不是調用者),更通用,減少代碼重複。 – frogge