How do draw FormattedText (if not in the onRender method)

I draw some Ellipse and add them to a Grid.

Then I'd like to add some FormattedText to each Ellipse. This i could do by getting the RectangleBounds of the Ellipse.

But following this example:

I need a DrawingContext to draw the text. But if I don't wantto override onRender, how can I get a DrawingContext?


You can use a DrawingGroup instead. It has an Open method that returns a DrawingContext and you can use that to construct a drawing.

You'll then need to arrange for that drawing to appear in the UI somehow. The easiest way is to wrap it in a DrawingBrush and use that to paint some existing element in the UI. For example, if you've got an ellipse called myEllipse, this will set its Fill property to be a DrawingBrush based on a DrawingGroup that contains a single bit of FormattedText:

var drawing = new DrawingGroup();
using (var context = drawing.Open())
    var text = new FormattedText("This is some text",
        new Typeface("Calibri"),
    context.DrawText(text, new Point(0, 0));

var db = new DrawingBrush(drawing);
db.Stretch = Stretch.None;
myEllipse.Fill = db;

If you've already filled the Ellipse with something else, you have two choices. You could either add more content to this drawing - you can make as many calls into the context as you like. For example, if I add this immediately before the call to context.DrawText:

context.DrawRectangle(Brushes.Cyan, null, new Rect(0, 0, 300, 100));

I'll get a cyan background behind the text. (You'd need to adjust the coordinates in these examples to suit your layout, of course.)

But it's probably simpler to add an extra element to host the drawing, rather than trying to piggy-back it into an element that's there to do something else. So you could put a Rectangle element positioned directly over the Ellipse, and use a DrawingBrush such as this as the Fill for that Rectangle. The Rectangle won't actually look rectangular, because this DrawingBrush doesn't paint in its whole area. So the effect will look much the same as it would if you'd layered a TextBlock over an Ellipse.

Need Your Help

What is the reason not to use select *?


I've seen a number of people claim that you should specifically name each column you want in your select query.

Error when creating an executable test-jar in Maven

unit-testing maven jar testng executable-jar

I'm trying to create a JAR that I can put on a non development machine and run some unit tests that exercise a web service. I've read that there are many ways to do this in maven. I'm focusing on...

displayed insecure content from

flash flex https embed flash-cs6

So recently I noticed a flash video player I created started running in to insecure content issues when played through an https URL. I spent quite some time going through all the measures to make s...