Search code examples
c#textdrawstring

Flip text vertically using Drawstring


I have some code that writes some text to a defined region.

 graphics.DrawString(text, goodFont, Brushes.Black, textarea, stringFormat);

There are some cases where I would like to flip the text on the horizontal so that it goes from:

enter image description here

To

enter image description here

I have tried to measure the string width and take the inverse of that:

float w = graphics.MeasureString(text, goodFont).Width;
graphics.DrawString(text, goodFont, Brushes.Black, -w, 0, stringFormat);

but then my issue is that the text extends outside the boundary of the box I wish to draw it in (textarea).

I would like to flip the text on the horizontal while maintaining my box boundary. Can anybody point me in the right direction for how to accomplish my task?

Thanks in advance!

EDIT: I am trying to avoid having to create a bitmap and then do the transformation.


Solution

  • You can use graphics transformation. The easier I see is to use the this Matrix Constructor (Rectangle, Point[]) like this:

    Point[] transformPoints =
    {
        // upper-left:
        new Point(textarea.Right - 1, textarea.Top),
        // upper-right:
        new Point(textarea.Left + 1, textarea.Top),
        // lower-left:
        new Point(textarea.Right - 1, textarea.Bottom),
    };
    var oldMatrix = graphics.Transform; 
    var matrix = new Matrix(textarea, transformPoints);
    try
    {
        graphics.Transform = matrix;
        graphics.DrawString(text, goodFont, Brushes.Black, textarea, stringFormat);
    }
    finally
    {
        graphics.Transform = oldMatrix;
        matrix.Dispose();
    }
    

    P.S. Although @serhiyb posted similar answer a few seconds before mine, I think this is easier to understand - you define the transformation by simply specifying a source rectangle and how to transform its upper-left, upper-right and lower-left points.