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

moo*_*ara 0 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;

    }
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

在此处输入图片说明

And*_*lad 5

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

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