[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 text filled with random lines in C#

text filled with random lines

This example uses the following code to draw text filled with random lines.

// Draw the lined-filled text. private void Form1_Paint(object sender, PaintEventArgs e) { const string TXT = "C# Helper"; // Make the result smoother. e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; e.Graphics.Clear(this.BackColor); // Make a font. using (Font the_font = new Font("Times New Roman", 150, FontStyle.Bold, GraphicsUnit.Pixel)) { using (GraphicsPath path = new GraphicsPath()) { using (StringFormat string_format = new StringFormat()) { string_format.Alignment = StringAlignment.Center; string_format.LineAlignment = StringAlignment.Center; int cx = ClientSize.Width / 2; int cy = ClientSize.Height / 2; path.AddString(TXT, the_font.FontFamily, (int)the_font.Style, the_font.Size, new Point(cx, cy), string_format); } // Restrict drawing to the path. using (Region clip_region = new Region(path)) { e.Graphics.Clip = clip_region; // Fill the path with lines. Random rand = new Random(); int x0, y0, x1, y1; x0 = 0; x1 = ClientSize.Width; for (int i = 1; i < 75; i++) { y0 = rand.Next(0, ClientSize.Height); y1 = rand.Next(0, ClientSize.Height); e.Graphics.DrawLine(Pens.Black, x0, y0, x1, y1); } y0 = 0; y1 = ClientSize.Height; for (int i = 1; i < 75; i++) { x0 = rand.Next(0, ClientSize.Width); x1 = rand.Next(0, ClientSize.Width); e.Graphics.DrawLine(Pens.Black, x0, y0, x1, y1); } // Reset the clipping region. e.Graphics.ResetClip(); } } } }

The interesting part of the code starts when the program creates a GraphicsPath. It then creates a StringFormat object to determine how the string is displayed and calls the GraphicsPath's AddString method to add the text to the path.

Next the code converts the GraphicsPath into a Region and calls the Graphics object's SetClip method to restrict future drawing to the Region. The program then draws a bunch of random lines across the form. The Graphics object restricts them to the clipping region so only the parts of the lines within the text are drawn.

The code finishes by resetting the clipping region so future graphics can use the whole form.

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

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