C#中的旋转文本对齐

我需要能够旋转标签中的文本并将其与左,右或中心对齐。 到目前为止,我能够在派生标签的onPaint方法中使用此代码进行旋转:

float width = graphics.MeasureString(Text, this.Font).Width; float height = graphics.MeasureString(Text, this.Font).Height; double angle = (_rotationAngle / 180) * Math.PI; graphics.TranslateTransform( (ClientRectangle.Width + (float)(height * Math.Sin(angle)) - (float)(width * Math.Cos(angle))) / 2, (ClientRectangle.Height - (float)(height * Math.Cos(angle)) - (float)(width * Math.Sin(angle))) / 2); graphics.RotateTransform(270f); graphics.DrawString(Text, this.Font, textBrush, new PointF(0,0), stringFormat); graphics.ResetTransform(); 

它工作正常。 我可以看到文字旋转了270度。

但是当我尝试在stringFormat中设置对齐时,它变得疯狂,我无法弄清楚发生了什么。

如何将文本旋转270度并将其对齐?

如果有人正在寻找提示,这里是0,190,180,270和360度旋转的解决方案,其中StringAligment工作。

有一点是选择正确的点来移动原点,第二个是根据旋转修改显示矩形。

 StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; SizeF txt = e.Graphics.MeasureString(Text, this.Font); SizeF sz = e.Graphics.VisibleClipBounds.Size; //90 degrees e.Graphics.TranslateTransform(sz.Width, 0); e.Graphics.RotateTransform(90); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Height, sz.Width), format); e.Graphics.ResetTransform(); //180 degrees e.Graphics.TranslateTransform(sz.Width, sz.Height); e.Graphics.RotateTransform(180); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Width, sz.Height), format); e.Graphics.ResetTransform(); //270 degrees e.Graphics.TranslateTransform(0, sz.Height); e.Graphics.RotateTransform(270); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Height, sz.Width), format); e.Graphics.ResetTransform(); //0 = 360 degrees e.Graphics.TranslateTransform(0, 0); e.Graphics.RotateTransform(0); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(0, 0, sz.Width, sz.Height), format); e.Graphics.ResetTransform(); 

如果您将此代码放在label的OnPaint事件中,它将显示您的旋转表单的标题四次。

如果你需要在非0 X,Y处绘制,扩展Adrian Serafin的答案:

 //90 degrees e.Graphics.TranslateTransform(sz.Width, 0); e.Graphics.RotateTransform(90); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(sz.ToPointF().Y, sz.ToPointF().X, sz.Height, sz.Width), format); e.Graphics.ResetTransform(); //180 degrees e.Graphics.TranslateTransform(sz.Width, sz.Height); e.Graphics.RotateTransform(180 this.Font, Brushes.Black, new RectangleF(-sz.ToPointF().X, -sz.ToPointF().Y, sz.Width, sz.Height), format); e.Graphics.ResetTransform(); //270 degrees e.Graphics.TranslateTransform(0, sz.Height); e.Graphics.RotateTransform(270); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(-sz.ToPointF().Y, sz.ToPointF().X, sz.Height, sz.Width), format); //0 = 360 degrees e.Graphics.TranslateTransform(0, 0); e.Graphics.RotateTransform(0); e.Graphics.DrawString(Text, this.Font, Brushes.Black, new RectangleF(sz.ToPointF().X, sz.ToPointF().Y, sz.Width, sz.Height), format); e.Graphics.ResetTransform();