Rotate Text for printing

2020-02-12 04:46发布

问题:

I am using a PrintDocument to print a page. At one point I want to rotate the text 90 degrees and print it ie print text vertically. Any ideas ???

g.RotateTransform(90);

does not work for OnPaint.

回答1:

When you call RotateTransform you will need to pay attention to where the coordinate system ends up. If you run the following code, the "Tilted text" will appear to the left of the left edge; so it's not visible:

e.Graphics.Clear(SystemColors.Control);
e.Graphics.DrawString("Normal text", this.Font, SystemBrushes.ControlText, 10, 10);
e.Graphics.RotateTransform(90);
e.Graphics.DrawString("Tilted text", this.Font, SystemBrushes.ControlText, 10, 10);

Since you have tilted the drawing surface 90 degrees (clock wise), the y coordinate will now move along the right/left axis (from your perspective) instead of up/down. Larger numbers are further to the left. So to move the tilted text into the visible part of the surface, you will need to decrease the y coordinate:

e.Graphics.Clear(SystemColors.Control);
e.Graphics.DrawString("Normal text", this.Font, SystemBrushes.ControlText, 10, 10);
e.Graphics.RotateTransform(90);
e.Graphics.DrawString("Tilted text", this.Font, SystemBrushes.ControlText, 10, -40);

By default the coordinate system has its origo in the top left corner of the surface, so that is the axis around which RotateTransform will rotate the surface.

Here is an image that illustrates this; black is before call to RotateTransform, red is after call to RotateTransform(35):