Mega Code Archive
Draw text to the background of a control by accessing the controls DrawingContext
Sample Text
//File:Window.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1() : base()
{
InitializeComponent();
}
private void WindowLoaded(object sender, EventArgs e)
{
myLabel.Background = new DrawingBrush(DrawMyText("My Custom Label"));
myButton.Background = new DrawingBrush(DrawMyText("Display Text"));
}
private Drawing DrawMyText(string textString)
{
DrawingGroup drawingGroup = new DrawingGroup();
using (DrawingContext drawingContext = drawingGroup.Open())
{
FormattedText formattedText = new FormattedText(
textString,
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Comic Sans MS Bold"),
48,
Brushes.Black
);
Geometry textGeometry = formattedText.BuildGeometry(new Point(20, 0));
drawingContext.DrawRoundedRectangle(Brushes.PapayaWhip, null, new Rect(new Size(formattedText.Width + 50, formattedText.Height + 5)), 5.0, 5.0);
drawingContext.DrawGeometry(Brushes.Gold, new Pen(Brushes.Maroon, 1.5), textGeometry);
return drawingGroup;
}
}
public void OnButtonClick(object sender, EventArgs e)
{
myCanvas.Background = new DrawingBrush(DrawMyText(myTextBox.Text));
}
}
}