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 =

    // 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.

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 Example   Follow me on Twitter   RSS feed

This entry was posted in drawing, fonts, graphics, strings and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

1 Response to Draw text filled with random lines in C#

  1. Pingback: Draw text filled with random colored lines in C# -

Comments are closed.