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 circle 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?
Share
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
Graphicsclass. All form controls have aCreateGraphics()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 thatGraphicsinstance, you can call various Draw methods (likeDrawCircle()) to put shapes on the screen. You will need to read up on thePen,BrushandColorobjects; they allow you to define the border, fill, and color of your circle. I would place the drawing logic in the control’sOnPaint()method, which is called whenever the window is told to redraw itself. To have your object move at regular intervals, set up aTimerwith some regular interval, and subscribe to itsTickevent with a handler that will perform the moving logic. After you make each move, callInvalidate()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. APanelorPictureBoxtaking up a span in the form window is the go-to method for custom graphics. You may also consider implementing double-buffered graphics using aBufferedGraphicsContextobject, or rolling your own by drawing your custom shapes on aBitmapthat you then set as the image for aPictureBox.