[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw an ellipse that sort of looks like a button in C#


This example uses two LinearGradientBrushes to draw an ellipse that has a sort of three-dimensional button-like appearance. The key is to outline the ellipse and then fill it with brushes whose gradients point in opposite directions.

The following code shows how this program draws its ellipses.

// Draw the button-like ellipse. private void Form1_Paint(object sender, PaintEventArgs e) { // Clear. e.Graphics.Clear(this.BackColor); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // Get the area we will fill. Rectangle rect = new Rectangle(30, 30, this.ClientSize.Width - 60, this.ClientSize.Height - 60); // Fill the ellipse. using (LinearGradientBrush br = new LinearGradientBrush(rect, Color.Lime, Color.DarkGreen, 225f)) { e.Graphics.FillEllipse(br, rect); } // Outline the ellipse. using (LinearGradientBrush br = new LinearGradientBrush(rect, Color.Lime, Color.DarkGreen, 45f)) { using (Pen pen = new Pen(br, 20f)) { // e.Graphics.DrawRectangle(Pens.Red, rect); rect.X += 10; rect.Y += 10; rect.Width -= 20; rect.Height -= 20; e.Graphics.DrawEllipse(pen, rect); } } }

This code clears the Graphics object and makes it draw smoothly. It then defines a rectangle to hold the ellipse.

Next the code fills the ellipse with a brush that changes from lime to dark green in the direction of 225 degrees. (Lower right to upper left.)

The program then creates a 20-pixel wide pen using a brush that flows from lime to dark green in the opposite direction: 45 degrees. (Upper left to lower right.)

If you were to use the pen to draw the ellipse at this point, the 20-pixel wide line would lie half inside and half outside of the ellipse. To make the outline lie completely within the ellipse it just filled, the program shifts the rectangle that defines the ellipse by half of the pen's thickness. It also decreases the rectangle's width and height by the pen's thickness.

Finally the program outlines the adjusted ellipse with a brush that flows from lime to dark green in the opposite direction (45 degrees).

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.