C# drawing and invalidating 2 lines to meet

Posted by BlueMonster on Stack Overflow See other posts from Stack Overflow or by BlueMonster
Published on 2012-04-12T04:52:35Z Indexed on 2012/04/12 5:29 UTC
Read the original article Hit count: 196

Filed under:
|
|
|

If i have 2 lines on a page as such:

   e.Graphics.DrawLine(blackPen, w, h, h, w);
   e.Graphics.DrawLine(blackPen, w2, h2, h2, w2); 

how would i animate the first line to reach the second line's position?

I have the following method which calculates the distance between two points (i'm assuming i would use this?)

   public int Distance2D(int x1, int y1, int x2, int y2)
   {
            //     ______________________
            //d = √ (x2-x1)^2 + (y2-y1)^2
            //

            //Our end result
            int result = 0;
            //Take x2-x1, then square it
            double part1 = Math.Pow((x2 - x1), 2);
            //Take y2-y1, then sqaure it
            double part2 = Math.Pow((y2 - y1), 2);
            //Add both of the parts together
            double underRadical = part1 + part2;
            //Get the square root of the parts
            result = (int)Math.Sqrt(underRadical);
            //Return our result
            return result;
    }

How would i re-draw the line (on a timer) to reach the second line's position? I've looked a lot into XAML (story-boarding) and such - but i want to know how to do this on my own. Any ideas? I know i would need a method which runs in a loop re-drawing the line after moving the position a tid bit. I would have to call Invalidate() in order to make the line appear as though it's moving... but how would i do this? how would i move that line slowly over to the other line? I'm pretty sure i'd have to use double buffering if i'm doing this as well... as such:

 SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);

This doesn't quiet work, i'm not quiet sure how to fix it. Any ideas?

protected override void OnPaint(PaintEventArgs e)
{
    Distance2D(w, h, w2, h2);
    if (w2 != w && h2 != h)
    {
        e.Graphics.DrawLine(blackPen, (w * (int)frame), (h * (int)frame), (h * (int)frame), (w * (int)frame));
        e.Graphics.DrawLine(blackPen, w2, h2, h2, w2);
    }
    else
    {
        t.Abort(); 
    }
    base.OnPaint(e);
}




public void MoveLine()
        {
            for (int i = 0; i < 126; i++)
            {
                frame += .02;
                Invalidate();
                Thread.Sleep(30);
            }
        }

private void button1_Click(object sender, EventArgs e)
        {
            t = new Thread(new ThreadStart(MoveLine));
            t.Start();
        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET