Reputation: 11
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#?
Upvotes: 1
Views: 1555
Reputation: 67301
you can try this like this:
Short explanation:
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);
}
}
}
}
Upvotes: 1