使用Drawstring垂直翻转文本

时间:2016-08-18 18:00:20

标签: c# text drawstring

我有一些代码可以将一些文本写入已定义的区域。

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

在某些情况下,我想在水平方向上翻转文字,以便它来自:

enter image description here

enter image description here

我曾尝试测量字符串宽度并采用相反的方法:

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

然后我的问题是文本扩展到我希望在(textarea)中绘制它的框的边界之外。

我想在保持盒子边界的同时翻转水平文本。任何人都能指出我如何完成任务的正确方向吗?

提前致谢!

编辑:我试图避免创建位图然后进行转换。

3 个答案:

答案 0 :(得分:3)

您可以使用Matrix Constructor转换图形,然后使用DrawString方法绘制图形。

试试这个:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    string text = "This is a Test";
    g.DrawString(text, Font, Brushes.Black, 0, 0);

    g.MultiplyTransform(new Matrix(-1, 0, 0, 1, 68, 50));

    g.DrawString(text, Font, Brushes.Black, 0, 0);
    g.ResetTransform();
}

<强>输出:

enter image description here

答案 1 :(得分:2)

您可以{/ 3}}使用

类似的东西:

float w = graphics.MeasureString(text, goodFont).Width;
graphics.MultiplyTransform(new Matrix(-1, 0, 0, 1, w, 0));
/*
 Matrix:
 -1 0
  0 1
 newX -> -x
 newY -> y
 and dx offset = w (since we need to move image to right because of new negative x)
*/
graphics.DrawString(text, goodFont, Brushes.Black, textarea, stringFormat);
graphics.ResetTransform();

您可能需要使用矩阵/区域参数,因为我盲目地编码,但我希望您有这个想法。

答案 2 :(得分:2)

您可以使用图形转换。我看到的更容易就是使用这个Matrix Constructor (Rectangle, Point[])

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。尽管@serhiyb在我的前几秒发布了类似的答案,但我认为这更容易理解 - 您只需指定一个源矩形以及如何变换其左上角,右上角和左下角来定义变换。 p>

相关问题