How to Draw a String, Square, Rectangle, Circle, Ellipse, and Polygon in Microsoft Visual C# (C Sharp)
Draw strings, squares, rectangles, circles, ellipses, and polygons in Microsoft Visual C#.
Instructions
-
-
1
Note: This article assumes you have installed Microsoft Visual C# 2008 Express Edition. You may download it for free from here: http://www.microsoft.com/express/download/
Open Microsoft Visual C#. Click on "Project..." to the right of Create in the Recent Projects area of the Start Page.
The New Project window will open. Click on "Windows Forms Application", enter a Name, and click OK.
By default, the only form in the project will be called "Form1" and you will be in Design mode for that form.
- 2
-
- 3
- 4
- 5
-
6
Add the following code in the Form1_Paint method:
// DrawString(string s, Font font, Brush brush, float x, float y)
e.Graphics.DrawString("C# rocks!", new Font("Arial", 12), Brushes.White, 15, 10);
e.Graphics.DrawString("C# rocks!", new Font("Arial", 12), Brushes.Black, 16, 11);// FillRectangle(Brush brush, int x, int y, int width, int height)
e.Graphics.FillRectangle(Brushes.White, 15, 35, 50, 50);
e.Graphics.DrawRectangle(Pens.Red, 15, 35, 50, 50);// FillEllipse(Brush brush, int x, int y, int width, int height)
e.Graphics.FillEllipse(Brushes.White, 15, 100, 50, 50);
e.Graphics.DrawEllipse(Pens.Red, 15, 100, 50, 50);// FillPolygon(Brush brush, Point[] points)
e.Graphics.FillPolygon(Brushes.White, new Point[3] { new Point(10, 210), new Point(40, 160), new Point(70, 210) });
e.Graphics.DrawPolygon(Pens.Red, new Point[3] { new Point(10, 210), new Point(40, 160), new Point(70, 210) });First we will draw a string with a shadow effect. The second parameter is a new Font object.
Then we draw various shapes. Note the the Draw methods use Pens and that Fill methods use Brushes.
Also note that the polygon methods take an array of Point objects. Each Point is an X and Y integer that represents the units away from the upper left corner.
- 7
- 8
-
1
Tips & Warnings
Play around with the Help. Tons of good stuff in there.
You might get addicted to C#. Watch out Java and C++ folks!!!