简体   繁体   中英

How to move a rectangle

I have pictureBox control in project and want move Rectangular2 with this code:

 int pointx1 = 140, pointx2 = 160, pointx3 = 160, pointx4 = 140, pointy1 = 180, pointy2 = 180, pointy3 = 240, pointy4 = 240;

    private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Refresh();
        Graphics graphic = pictureBox1.CreateGraphics();
        graphic.FillPolygon(new SolidBrush(Color.Black), new PointF[]{ new Point(100, 200), new Point(200, 200), new Point(200, 220), new Point(100, 220) });
        //Rectangular2 
        graphic.FillPolygon(new SolidBrush(Color.Blue), new PointF[] { new Point(pointx1++, pointy1++), new Point(pointx2++, pointy2++), new Point(pointx3++, pointy3++), new Point(pointx4++, pointy4++) });
    }

but i want use bitmap for draw and move Rectangular2, because its refresh and flashes.

The CreateGraphics is your enemy here. Use the Paint event of the PictureBox, which is already double-buffered, to do your drawing:

pictureBox1.Paint += pictureBox1_Paint;

void pictureBox1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.Clear(Color.White);
  e.Graphics.FillPolygon(new SolidBrush(Color.Black), 
                         new PointF[] { new Point(100, 200), 
                                        new Point(200, 200),
                                        new Point(200, 220),
                                        new Point(100, 220) });
  e.Graphics.FillPolygon(new SolidBrush(Color.Blue),
                         new PointF[] { new Point(pointx1, pointy1),
                                        new Point(pointx2, pointy2),
                                        new Point(pointx3, pointy3),
                                        new Point(pointx4, pointy4) });
}

Then use your timer to update your coordinates and invalidate your control:

private void timer1_Tick(object sender, EventArgs e) {
  pointx1++;
  pointy1++;
  pointx2++;
  pointy2++;
  pointx3++;
  pointy3++;
  pointx4++;
  pointy4++;
  pictureBox1.Invalidate();
}

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