在C#中旋转的文本对齐 [英] Rotated text align in C#

查看:163
本文介绍了在C#中旋转的文本对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to be able to rotate text in a label and align it to the left, right or center. So far I am able to do rotation with this code in the derived label's onPaint method:

 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度。

And it works fine. I can see text rotated 270 degrees.

但是,当我尝试设置的StringFormat对准它都疯了,我想不通这是怎么回事。

But when I try to set alignment in stringFormat it goes crazy, and I can't figure out what's going on.

我怎么能有文本旋转270度,并对准了?

How can I have text rotated by 270 degrees and align it to up?

推荐答案

在万一有人一直在寻找的提示,这里是0,90,180,270,和360度的旋转,其中StringAligment的工作方案。

In case somebody was looking for tips, here is the solution for 0, 90, 180, 270, and 360 degrees rotation, where StringAligment works.

一件事是选择用于移动原点,和第二个权点是根据旋转修改显示矩形

One thing was choosing the right point for moving the origin to, and the second one was to modify the display rectangle according to rotation.

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事件把这个代码,它会显示你的旋转窗体的标题四倍。

If you put this code in label's OnPaint event, it would display your rotated form's title four times.

这篇关于在C#中旋转的文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆