tags:

views:

172

answers:

2

I want to move a Diamond Shape in the form(for example 2 pixels every 200ms) horizantally. I used the following code in From_Paint Event.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Point p1 = new Point(5,0);
    Point p2 = new Point(10, 5);
    Point p3 = new Point(5, 10);
    Point p4 = new Point(0, 5);
    Point[] ps = { p1, p2, p3, p4, p1 };
    g.DrawLines(Pens.Black, ps);
}

I know how to move a picturebox but how to do with shape.

Thanks, Ani

A: 

use Timer then redraw on each tick.

Andrey
how can I increase points of Diamonds..on every tick till it hits end of form
Ani
+2  A: 

You'll need to track your current location in a form level variable. If you do this, your Form1_Paint event can change the X pixel location each time it draws.

Just add a Timer to your form, and set it's interval to 200ms. Each 200ms, add 2 to your current X pixel, and invalidate your control (so it redraws).


Edit: Add this to your form:

int xOffset = 0;

Then, in your timer_Tick:

private void timer1_Tick(object sender, EventArgs e)
{
    if (xOffset < 500)
        xOffset += 2;
    else
        timer1.Enabled = false; // This will make it only move 500 pixels before stopping.... Change as desired.

    this.Invalidate(); // Forces repaint
}

Change your paint event to:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    Point p1 = new Point(5 + xOffset,0);
    Point p2 = new Point(10 + xOffset, 5);
    Point p3 = new Point(5 + xOffset, 10);
    Point p4 = new Point(0 + xOffset, 5);
    Point[] ps = { p1, p2, p3, p4, p1 };
    g.DrawLines(Pens.Black, ps);
}
Reed Copsey
well these are my co-ordinates....how can make them increment 2pixel on every tick...I tried to use += operator but do not work.. Point p1 = new Point(5,0); Point p2 = new Point(10, 5); Point p3 = new Point(5, 10); Point p4 = new Point(0, 5);
Ani
You need to store, at the class level, an integer that's your X coordinate (or offset)...
Reed Copsey
@Ani: I added code to demonstrate...
Reed Copsey
@Reed Thanks a lot...I was missing Offset...I ll try this approach..Thanks a lot..your help appreciated
Ani
@Ani: You can just store the coordinate instead of an offset, and use that instead, if you wish, too... This will work well, though.
Reed Copsey
@Reed Is there anyway to move it only till edge of form....and bounce it back..I know we have to decrease xOffset but how to detect edge of formThanks
Ani