Draw text filled with a picture in C#

This program uses two images added to the project as resources. To add resources to the project, open the Project menu and select the Properties command at the very bottom. On the Properties page, click the Resources tab. Now you can use the Add Resource dropdown menu to add existing or new files to the program's resources.

This program draws two pieces of text filled with pictures. It first uses the following code to fill text with a single big image.


// Make the bitmap we will display.
Bitmap bm = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
using (Graphics gr = Graphics.FromImage(bm))
{
gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
gr.Clear(this.BackColor);

// Make text filled with a single big image.
// Make a brush containing the picture.
using (TextureBrush the_brush = new TextureBrush(Properties.Resources.ColoradoFlowers))
{
// Draw the text.
using (Font the_font = new Font("Times New Roman", 150, FontStyle.Bold))
{
gr.DrawString("Flowers", the_font, the_brush, 0, 0);
}
}
...

This code creates a Bitmap and a Graphics object associated with it. It sets the Graphics object's TextRenderingHint to make the text smoother.

Next the code creates a TextureBrush holding the large image contained in the ColoradoFlowers resource. It makes a big font and then uses DrawString to draw the text, filling it with the brush.

Note: Depending on where the text is drawn and where the brush's origin is, the image may not fit the text nicely. For example, the edge of the image may run through the middle of the text. In that case, DrawString will repeat the image as needed but you may see the border between two copies of the image and that may look ugly. If necessary, you can use the brush's TranslateTransform method to move the brush's origin so it lines up with the text better.

After drawing the first piece of text, the program uses the following code to draw the second.

    ...
// Make text filled with a tiled image.
// Make a brush containing the picture.
using (TextureBrush the_brush = new TextureBrush(Properties.Resources.Smiley))
{
// Draw the text.
using (Font the_font = new Font("Times New Roman", 150, FontStyle.Bold))
{
gr.DrawString("Smile!", the_font, the_brush, 75, 175);
}
}
}

// Display the result.
this.BackgroundImage = bm;

This code creates another TextureBrush using a different image resource. This time the resource is small so it is tiled to fill the text. You can see the different results in the picture of the program at the beginning of this blog entry.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.