如何在C#中绘制高质量的旋转字符串?

时间:2011-12-19 11:39:40

标签: c# graphics user-controls

我想绘制一个字符串并使用自定义角度旋转它。简单地说,我计算包含旋转图像的区域的新尺寸,然后创建一个位图对象,并通过它的图形对象,我绘制一个包含3个变换的字符串(平移到中心,旋转和反向平移)。我写了下面的代码,但质量不合适。有没有人有想法?

    private Image RotateText(string Text, int FontSize, float Angle)
    {

        //Modify angle
        Angle *= -1;

        //Calculate rotation angle in radian
        double AngleInRadian = (Angle * 2 * Math.PI) / 360d;

        //Instantiate a font for text
        Font TextFont = new Font("Tahoma", FontSize, FontStyle.Bold);

        //Measure size of the text
        Graphics Graphic = this.CreateGraphics();
        SizeF TextSize = Graphic.MeasureString(Text, TextFont);

        //Calculate size of the rotated text
        double NewWidth  = Math.Abs(TextSize.Width * Math.Cos(AngleInRadian)) + Math.Abs(TextSize.Height * Math.Sin(AngleInRadian));
        double NewHeight = Math.Abs(TextSize.Width * Math.Sin(AngleInRadian)) + Math.Abs(TextSize.Height * Math.Cos(AngleInRadian));

        //Instantiate a new image for rotated text
        Bitmap RotatedText = new Bitmap((int)(Math.Round(NewWidth)), (int)(Math.Round(NewHeight)));

        //Get graphic object of new isntantiated image for painting
        Graphics TextGraphic = Graphics.FromImage(RotatedText);
        TextGraphic.InterpolationMode = InterpolationMode.High;

        //Calcaute coordination of center of the image
        float OX = (float)NewWidth  / 2f;
        float OY = (float)NewHeight / 2f;

        //Apply transformations (translation, rotation, reverse translation)
        TextGraphic.TranslateTransform(OX, OY);
        TextGraphic.RotateTransform(Angle);
        TextGraphic.TranslateTransform(-OX, -OY);

        //Calculate the loaction of drawing text
        float X = (RotatedText.Width  - TextSize.Width ) / 2f;
        float Y = (RotatedText.Height - TextSize.Height) / 2f;

        //Draw the string
        TextGraphic.DrawString(Text, TextFont, Brushes.White, X, Y);

        //Return the image of rotated text
        return RotatedText;

    }

结果如下:

enter image description here

2 个答案:

答案 0 :(得分:3)

尝试将TextRenderingHint对象的Graphics属性设置为AntiAlias

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx

答案 1 :(得分:-1)

您可以尝试以下几点:

  • 在您的XAML中:

    TextOptions.TextFormattingMode =“显示”(和其他TextOptions附加属性)

  • 在您的C#中:

    TextOptions.SetTextFormattingMode(this,TextFormattingMode.Display);

  • 查看this SO主题