如何在xamarin.android中为自定义属性设置动画

时间:2017-06-21 10:50:51

标签: c# xamarin xamarin.android

我画了一行。我在视图中添加了AngleProperty。使用该角度属性我需要将该线设置为该角度的动画。

这是我的视图,其中绘制了一行

public class DrawView : View
    {
        Paint paint = new Paint();

        private double mvalue = 90;
         public double Angle
        {
            get { return mvalue; }
            set { 
                ObjectAnimator anim = ObjectAnimator.OfFloat(this, "Angle", (float)this.Angle, (float)value);
                anim.SetDuration(500);
                anim.Start();
                mvalue = value;

            }
        }
        public DrawView(Context context):base(context)
        {
            paint.Color = Color.Green;
        }

        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);
            Value = Angle* Math.Pi / 180;
        var startX = 300;
        var startY = 300;
        var endX = 500 + 40 * Math.Sin(Value);
        var endY = 500 + 40 * Math.Cos(Value);

        canvas.DrawLine(startX, startY, (float)endX, (float)endY, paint);        
        }
    }

在主Activity中,我添加了一个角度给出的按钮,

 public class MainActivity : Activity
    {
        DrawView drawview;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
 drawview = new DrawView(this);
            Button b = new Button(this);
            b.SetHeight(50);
            b.SetWidth(50);
            b.Click += B_Click;
            LinearLayout lay = new LinearLayout(this);
            lay.AddView(b);
            lay.AddView(drawview);
}
 private void B_Click(object sender, System.EventArgs e)
        {
            drawview.Angle= 180;
        }
}

任何人都建议如何将该线设置为特定角度

1 个答案:

答案 0 :(得分:0)

逻辑是正确的,但有几个问题。由于您已定义了Angle属性,因此应使用Angle属性来控制动画而不是使用Value属性,然后它可以像this一样正常工作。有关详细信息,请阅读document

protected override void OnDraw(Canvas canvas)
    {
        base.OnDraw(canvas);
        Angle = Angle * Math.PI / 180;
        var startX = 300;
        var startY = 300;
        var endX = 500 + 40 * Math.Sin(Angle);
        var endY = 500 + 40 * Math.Cos(Angle);

        canvas.DrawLine(startX, startY, (float)endX, (float)endY, paint);
    }

点击按钮后,启动Animation

private void B_Click(object sender, System.EventArgs e)
    {
        //certain angle decided by EditText's text
        Int32 number = int.Parse(et.Text.ToString());
        drawview.Angle = number;
    }