-
Notifications
You must be signed in to change notification settings - Fork 3
How To: Draw To The Screen
This page assumes you already have a empty simulation working. See How To: Open a Window.
Simply drawing a rectangle is as easy as one method call in OnRender
:
public override void OnRender(ICanvas canvas)
{
// draw a 400 pixel by 300 pixel rectangle to the screen at (75, 125).
canvas.DrawRect(75, 125, 400, 300);
}
Some methods on
ICanvas
have an optional parameter,alignment
, which specifies how the given position should be interpreted relative to the shape. For example, specifyingAlignment.CenterRight
means that the (x,y) coordinate you provided is the center of the shape's right edge (or, in some cases, that of the shape's bounding rectangle).
Recall that OnRender()
is called once per frame, and that frames happen pretty frequently. So, if we redraw our rectangle in every frame, but offset it by a small amount, it should look like it's moving. Let's do it:
// keeps track our rectangle's x position;
int x = 0;
public override void OnRender(ICanvas canvas)
{
// draw the rectangle
canvas.DrawRect(x, 200, 100, 100);
// change the X coordinate for next frame
x += 5;
}
Running this now gives a moving rectangle! But it's not quite what we're looking for - the rectangle just grows horizontally. This is because we are not clearing the screen: each frame we are drawing over the last frame's rectangle, just offset by 5 pixels. We need to clear the screen before we do any drawing.
To resolve this, we just add one call to ICanvas.Clear(Color)
before we do all of our drawing:
public override void OnRender(ICanvas canvas)
{
canvas.Clear(Color.Red); // or whatever color you want...
// rest of drawing code here...
}