开发者

How do I create an object and paint it while it moves?

I want to create a circle object, put it on the screen with a velocity, and have it bounce around within the borders. I can setup the circ开发者_如何学Cle class just fine, but how do I paint the object (and multiple ones later, say click and you get more circle objects) and show its movement?


Start with overriding OnPaint method on the Form and add draw logic there

protected override void OnPaint(PaintEventArgs e)
{
    e.Graphics.DrawEllipse(new Pen(Color.Red), 0, 0, 100, 100);
}


Drawing can be accomplished in at least 3 different ways in .NET (WFA, WPF, and XNA frameworks). For this answer I will assume you're using the simplest: a WinForms app.

Drawing/painting custom shapes in .NET is accomplished using the Graphics class. All form controls have a CreateGraphics() method, which gives you a reference to a "box" on the screen with the size and location of the control on which you called the method. Using that Graphics instance, you can call various Draw methods (like DrawCircle()) to put shapes on the screen. You will need to read up on the Pen, Brush and Color objects; they allow you to define the border, fill, and color of your circle. I would place the drawing logic in the control's OnPaint() method, which is called whenever the window is told to redraw itself. To have your object move at regular intervals, set up a Timer with some regular interval, and subscribe to its Tick event with a handler that will perform the moving logic. After you make each move, call Invalidate() on the control you have the Graphics handle for; that will cause the control to redraw itself. I would avoid getting the graphics handle for an entire form, or any control on which you place other nested controls, because a control that is repainting itself will also tell all its nested controls to repaint themselves. A Panel or PictureBox taking up a span in the form window is the go-to method for custom graphics. You may also consider implementing double-buffered graphics using a BufferedGraphicsContext object, or rolling your own by drawing your custom shapes on a Bitmap that you then set as the image for a PictureBox.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜