Drawing vertical text in WPF using DrawingContext.DrawText()
Asked Answered
B

3

11

I am doing some custom drawing using DrawingContext in WPF. I am using DrawingContext.DrawText for drawing strings. Now, at a place I want to draw the text vertically. Is there any option in the DrawingContext OR DrawText() function to draw text vertically?

Braasch answered 11/1, 2012 at 6:49 Comment(0)
I
14

You will have to use PushTransform and Pop methods of DrawingContext class.

DrawingContext dc; // Initialize this correct value
RotateTransform RT = new RotateTransform();
RT.Angle = 90
dc.PushTransform(RT)
dc.DrawText(...);
dc.Pop();
Igenia answered 11/1, 2012 at 7:0 Comment(0)
C
5
DrawingContext dc;
Point textLocation
var RT = new RotationTransform(-90.0);

// You should transform the location likewise...
location = new Point(-location.Y, location.X);

dc.PushTransform(RT);
dc.DrawText(formattedText, location);

Sorry, I had to post this because I was hitting my head against a wall for fifteen minutes trying to figure this out. I don't want anyone else to go through that.

Chancellor answered 12/6, 2014 at 19:59 Comment(1)
Altough this answer is rather old I'd like to add that transforming the location should be done by another transformation object rather than 'manually' exchanging the values of the Point() ctor, which works with an angle of 90, only. When creating a TranslateTransform object with the text location and pushing it before the rotation, then the code will work with any angle.Turtleback
T
4

Here is my solution: It is need to create rotate transform around the text origin, so we pass x and y to RotateTransform constructor

       ...
        // ft - formatted text, (x, y) - point, where to draw            
        dc.PushTransform(new RotateTransform(-90, x, y));
        dc.DrawText(ft, new Point(x, y));
        dc.Pop();
        ...
Tredecillion answered 20/2, 2017 at 11:31 Comment(2)
Please consider adding some text to explain your answer.Narcotic
It simply makes sense to define the point of rotation with RotateTransform for general use. x and y are the text position coordinates.Tomi

© 2022 - 2024 — McMap. All rights reserved.