Skip to content
CShift0.45

2D graphics: System.Drawing and System.Graphics

← Documentation

Everything a 2D game needs to draw, in the standard library, on Windows, Linux and in the browser: a window, the keyboard and the mouse, a canvas that draws into an image, bitmap fonts, sprite sheets, and a game loop with a steady frame rate. There is nothing to install and no C library to link. Sound is a separate part, System.Audio.

Namespace What
System.Drawing the basic types: Color, Point, Size, Rect, Vector2
System.Image Image (the pixels) and the files PNG, BMP and PPM (stdlib.md)
System.Graphics Window, Input, Key, Canvas, Font, SpriteSheet, Flip, Scaling, Cursor, Clipboard
System.Ui buttons, text boxes and the other widgets (ui.md); built on System.Graphics

cshiftc new game2d (cli.md) makes a project that starts with all of this.

using System;
using System.Drawing;
using System.Graphics;
using System.Image;
const int Width = 320;
const int Height = 180;
int Main()
{
var window = try Window.Open("Game", Width * 3, Height * 3);
window.SetFrameRate(60);
var screen = Image.Create(Width, Height); // the picture the game draws
var canvas = Canvas.Create(screen);
var player = Vector2.Create(40.0, 80.0);
while (window.Update()) // waits for the next frame; false once the window is closed
{
var input = window.Input();
if (input.JustPressed(Key.Escape))
break;
if (input.IsDown(Key.Right))
player.X += 90.0 * window.DeltaTime(); // 90 pixels a second, whatever the frame rate
canvas.Clear(Color.FromRgb(0x1E2A44u));
canvas.FillRect(Rect.Create(0, Height - 8, Width, 8), Color.DarkGray());
canvas.FillRect(Rect.Create(player.ToPoint().X, player.ToPoint().Y, 16, 16), Color.Orange());
canvas.Text(Font.Tiny5x7(), 4, 4, "SCORE 0", Color.White());
window.ShowScaled(screen); // 320 x 180, scaled up with sharp pixels
}
return 0;
}
  • Window.Update handles the events of the window and waits until the next frame is due: SetFrameRate(60) makes it 60 frames a second (without it the loop runs as fast as it can). In the browser the page’s frames set the pace.
  • Window.DeltaTime is the time of the last frame in seconds (at most 0.1, so that nothing jumps after the window was dragged). Movement multiplied by it is the same at any frame rate.
  • Window.ShowScaled(screen) shows the picture as large as fits with a whole factor (2x, 3x, …), centered, the rest black. ShowScaled(screen, Scaling.Fit) uses any factor, Scaling.Stretch fills the window. Window.Show(image) shows an image one to one.
  • The game’s loop is an ordinary loop also in the browser (cshiftc publish): Update returns to the page for each frame and continues where it was (wasm.md).
Type What
Color A, R, G, B (0 to 255). Color.FromRgb(255, 128, 0), Color.FromRgb(0xFF8000u) (CSS notation), Color.FromArgb(0x80FF8000u), Color.FromHsv(hue, s, v); Black(), White(), Red(), Orange(), … Transparent(); WithAlpha(128), Lerp(other, t), Scale(0.5) (darker), Over(background), ToArgb()
Point X, Y: Point.Create(x, y), Add, Subtract, Offset(dx, dy), Scale, ToVector()
Size Width, Height: Area(), IsEmpty(), Scale
Rect X, Y, Width, Height (the right and bottom edges are outside): Rect.Create(x, y, w, h), Rect.FromEdges, Right(), Bottom(), Position(), Size(), Center(), Contains(x, y) / Contains(point) / Contains(rect), Intersects(other) (a collision), Intersect(other) (the overlap), Union, Offset, Shrink
Vector2 X, Y as double, for positions and speeds with fractions: Add, Subtract, Scale, Dot, Length, DistanceTo, Normalized, Lerp, ToPoint() (rounded)

All of them can be compared (Equals) and used as keys of a Dictionary (except Vector2).

Window.Open(title, width, height) opens a window whose inside is width x height pixels (on a screen with a higher scale, such as 150 %, it is larger by that factor; Window.Width()/Height() are the real pixels). One window at a time. It fails with a WindowError: NotSupported (no windows on the target: macOS for now, WebAssembly outside of a browser), NoDisplay (Linux without an X server), CannotCreate.

Update() handles the events and waits (see above); false once the window is closed
Input() the keyboard and the mouse of this frame (see below)
Show(image), ShowScaled(screen), ShowScaled(screen, scaling) shows a frame
SetFrameRate(fps), DeltaTime() the pace of the loop
ToScreen(input), ToScreen(x, y) the mouse in pixels of the picture of ShowScaled (it may lie on the black border, outside of the picture)
SetTitle, SetCursor(Cursor.Crosshair), SetDarkFrame, ConfirmClose, Close the window itself
Width(), Height(), Scale() its size and the scale of its screen
Platform Window
Windows Win32 and GDI
Linux X11: libX11 is loaded when the window opens (every desktop has it; building needs no X11 headers)
The browser the <canvas> of the page (cshiftc publish, cshiftc serve)
AmigaOS 3.0 an Intuition window; the frames of a System.Ui are shown, a whole image (Show) not yet

window.Input() gives an Input for the frame:

IsDown(key) the key is held (a game walks while an arrow key is held)
JustPressed(key), JustReleased(key) the key went down or up in this frame, once per press
Pressed(key) the key was pressed since the last frame, with the repeats of a held key (as typing works); Pressed(Key.S, KeyModifiers.Ctrl) is Ctrl+S
Ctrl, Shift, Alt the modifier keys
Text the characters typed (UTF-8)
MouseX, MouseY, MousePosition() the mouse in pixels of the window (-1 outside); window.ToScreen(input) in pixels of the picture
MouseDown/MousePressed/MouseReleased, RightDown/…, MiddleDown/… the buttons
Wheel, WheelX the mouse wheel in notches
Time seconds from a monotonic clock
CloseRequested the user wants to close the window (with ConfirmClose(true))

Key has the letters A to Z, the digits D0 to D9 and NumPad0 to NumPad9, F1 to F12, the arrows, Space, Enter, Escape, Tab, Backspace, Delete, Insert, Home, End, PageUp, PageDown, Plus, Minus, Comma and Period.

A Canvas draws into an Image (Canvas.Create(image)); it shares the image’s pixels, so drawing changes the image. Everything is clipped to canvas.Clip (SetClip(rect)), and colors with an alpha below 255 are blended with what is there.

Clear(color) the whole image (ignores the clip)
FillRect(rect, color), StrokeRect(rect, width, color) rectangles
FillRoundRect, StrokeRoundRect rounded rectangles (smooth edges)
FillCircle(cx, cy, r, color), Line(x0, y0, x1, y1, width, color) smooth circles and lines; the coordinates may lie between pixels
Plot(x, y, color), PixelLine, PixelCircle, FillPixelCircle exact pixels without smooth edges, for pixel art
Text(font, x, y, text, color) text (returns its width)
DrawImage(image, x, y) a whole image, blended by the alpha of its pixels
DrawImage(image, source, x, y), DrawImage(image, source, target) a part of an image (a tile), unscaled or scaled (nearest pixel)
DrawImage(image, source, x, y, flip), DrawImage(image, source, target, flip) mirrored: Flip.Horizontal, Flip.Vertical, Flip.Both

A camera is a position that is subtracted from what the game draws: canvas.DrawImage(tile, src, x - cameraX, y - cameraY).

var sheet = SpriteSheet.Create(try Image.Load("hero.png"), 16, 16); // frames of 16 x 16 pixels
int frame = (int)(time * 8.0) % 4; // 8 frames a second
sheet.Draw(ref canvas, frame, x, y, lookingLeft ? Flip.Horizontal : Flip.None);

A SpriteSheet cuts an image into frames of the same size, row by row (Spacing for pixels between them). Frame(index) and Frame(column, row) give the rectangle of a frame for DrawImage. Images come from Image.Load("data/hero.png") (PNG, BMP, PPM); in the browser the folder must be in the assets of cshift.json (wasm.md), or the image is built into the program: const ReadOnlySlice<uint8> Hero = embed("hero.png"); and Image.Decode(Hero).

Font.Tiny5x7() 5 x 7 pixels in cells of 6 x 8: digits, uppercase letters with Ä, Ö, Ü and ß, punctuation and arrows (lowercase letters are drawn as uppercase ones): for small game screens
Font.Fixed7x13(), Font.Fixed10x20() the “fixed” fonts of X11 with ASCII and Latin-1
font.Zoomed(2) every pixel as 2 x 2 pixels
Font.Parse(lines, width, height) a font of your own in a text format: a line with the character, then height lines with # for a set pixel
font.Measure(text), font.LineHeight(), font.CharWidth() sizes
var font = Font.Parse((try File.ReadAllText("font.txt")).Split('\n'), 6, 8);
canvas.Text(font.Zoomed(2), 10, 10, "GAME OVER", Color.Red());

A System.Ui.Ui draws its widgets with the same canvas and fonts and shows its frames in the same window (window.Show(ui)); see ui.md. A game can draw its own picture and show it, or show a Ui (a menu, an editor), frame by frame.