我需要能够旋转标签中的文字并将其与左,右或中心对齐。到目前为止,我能够在派生标签的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 :(得分:25)
如果有人正在寻找提示,这里是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();
如果您将此代码放在标签的OnPaint事件中,它会四次显示您的旋转表单的标题。
答案 1 :(得分:0)
如果你需要画一个非0 X,那么Adrian Serafin的答案的延伸,Y:
//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();