使用RotateTransform在其中心周围绘制旋转文本

Mar*_*o M 6 c# text drawstring rotation

我在C#中有这个代码来绘制旋转的文本

        Font font = new Font("Arial", 80, FontStyle.Bold);
        int nWidth = pictureBox1.Image.Width;
        int nHeight = pictureBox1.Image.Height;

        Graphics g = Graphics.FromImage(pictureBox1.Image);

        float w = nWidth / 2;
        float h = nHeight / 2;

        g.TranslateTransform(w, h);
        g.RotateTransform(90);

        PointF drawPoint = new PointF(w, h);
        g.DrawString("Hello world", font, Brushes.White, drawPoint);

        Image myImage=new Bitmap(pictureBox1.Image); 

        g.DrawImage(myImage, new Point(0, 0));

        pictureBox1.Image = myImage;
        pictureBox1.Refresh();
Run Code Online (Sandbox Code Playgroud)

如果没有旋转,文本将被绘制在图像的中心,但是使用RotateTransform,它会从图像中移出一半,旋转中心也会偏离.

如何仅在文本中心旋转文本?不影响图像上的文字位置.

Mic*_*Liu 6

如果要在图像的中心绘制旋转文本,则将文本的位置偏移文本的测量大小的一半:

using (Font font = new Font("Arial", 80, FontStyle.Bold))
using (Graphics g = Graphics.FromImage(pictureBox1.Image))
{
    float w = pictureBox1.Image.Width / 2f;
    float h = pictureBox1.Image.Height / 2f;

    g.TranslateTransform(w, h);
    g.RotateTransform(90);

    SizeF size = g.MeasureString("Hello world", font);
    PointF drawPoint = new PointF(-size.Width / 2f, -size.Height / 2f);
    g.DrawString("Hello world", font, Brushes.White, drawPoint);
}

pictureBox1.Refresh();
Run Code Online (Sandbox Code Playgroud)

(当你完成它们时,处理FontGraphics对象是个好主意,所以我添加了几个using语句.)

变体#1:此片段将文本的左上角定位在(400,200),然后围绕该点旋转文本:

g.TranslateTransform(400, 200);
g.RotateTransform(90);
PointF drawPoint = new PointF(0, 0);
g.DrawString("Hello world", font, Brushes.White, drawPoint);
Run Code Online (Sandbox Code Playgroud)

变体#2:此片段将文本的左上角定位在(400,200),然后围绕文本中心旋转文本:

SizeF size = g.MeasureString("Hello world", font);
g.TranslateTransform(400 + size.Width / 2, 200 + size.Height / 2);
g.RotateTransform(90);
PointF drawPoint = new PointF(-size.Width / 2, -size.Height / 2);
g.DrawString("Hello world", font, Brushes.White, drawPoint);
Run Code Online (Sandbox Code Playgroud)