2016-08-18 137 views
1

我有一些代码将某些文本写入到已定义的区域。使用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)中绘制它的框的边界之外。

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

在此先感谢!

编辑:我试图避免必须创建一个位图,然后进行转换。

回答

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

+0

这个解决方案给了我什么,我需要。非常感谢。 – markdozer

2

您可以使用Transformation Matrix

喜欢的东西:

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(); 

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

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