Title: Draw text filled with a picture in C#
This example shows how you can draw text filled with a picture that is added to the project as a resource.
(To add resources to a 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.)
When it loads, the example uses the following code to draw text filled with a picture of some flowers.
// Make the image.
private void Form1_Load(object sender, EventArgs e)
{
// 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", 50, FontStyle.Bold))
{
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
gr.DrawString("Happy\nMother's Day!",
the_font, the_brush, this.ClientRectangle, sf);
}
}
}
}
// Display the result.
this.BackgroundImage = bm;
}
This code creates a Bitmap to fit the form 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 image contained in the ColoradoFlowers resource. It makes a big font. It then makes a StringFormat object and sets its Alignment and LineAlignment properties to center the text both verticallyi and horizontally.
The code then uses the DrawString method to draw the text, filling it with the brush and centered on the form's client area.
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 text, the program displays it on the form's background. By default the BackgroundImage property tiles, so if you enlarge the form, you'll see repeating copies of the text.
Download the example to experiment with it and to see additional details.
|