简体   繁体   中英

How to use animations to draw a straight line?

I want to draw a line in my code behind C# Universal app. I tried using the Line class and the line does show up, but I don't know how to make an animation so it looks like the line is being drawn in the screen instead of popping up, or instead of transferring it from outside of the screen to the location. I would like to see the animation drawing the line from point A to point B. Any idea how I can achieve this? Thanks!
I am very grateful if someone could provide an example of this
I have tried to follow this co unsuccessfully How do you animate a line on a canvas in C#?

you can try this like this:

Short explanation:

  • There are two Points p1 and p2. You can set them wherever you like.
  • The durationMS are the milliseconds the animation will take.
  • The stepMS are the milliseconds how often a new line is drawn.
  • The timer "tmr" does the animation work

we need to calculate the width of each step, the angle "k" of the line and its offset "d". Then we start the timer. Each "Tick" will do the same:

  • increase the step counter
  • calculate the new endpoint along the line
  • draw the line

    In the last step the line is drawn with a differen color from p1 to p2.

This is a Form's code...

using System;
using System.Drawing;
using System.Windows.Forms;

namespace TestSO {

    public partial class Form1 : Form {
        public Form1() { }

        PointF p1 = new PointF(10, 10);
        PointF p2 = new PointF(170, 30);

        float durationMS = 5000;
        float stepMS = 100;

        float stepWidthX;
        float k;
        float d;

        private Timer tmr = new Timer();

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            stepWidthX = (p2.X-p1.X)/ (durationMS / stepMS);

            k = (p2.Y - p1.Y) / (p2.X - p1.X);
            d = (p2.X * p1.Y - p1.X * p2.Y) / (p2.X - p1.X);

            tmr.Tick += tmr_Tick;
            tmr.Interval = (int)stepMS;
            tmr.Start();
        }

        private int stepCounter = 0;
        void tmr_Tick(object sender, EventArgs e) {
            stepCounter++;

            float x = p1.X + stepCounter * stepWidthX;
            float y = k * x + d;
            this.CreateGraphics().DrawLine(Pens.Black, p1, new PointF(x, y));


            if(stepCounter * stepMS > durationMS){
                stepCounter = 0;
                tmr.Stop();
                this.CreateGraphics().DrawLine(Pens.Red, p1, p2);
            }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM