[英]How to draw a rotated string with high quality in C#?
I want to draw a string and rotate it with a custom angle. 我想画一个字符串并用自定义角度旋转它。 Simply, I calculate the new dimenstions of the area that contains the rotated image, then create a bitmap object and by means of graphics object of it, I draw a string with 3 transformations (translation to the center, rotation, and reverse translation).
简单地说,我计算包含旋转图像的区域的新尺寸,然后创建一个位图对象,并通过它的图形对象,我绘制一个包含3个变换的字符串(平移到中心,旋转和反向平移)。 I wrote the following code but the quality is not desired.
我写了下面的代码,但质量不合适。 Does anyone have an idea?
有没有人有想法?
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;
}
The result is this: 结果是这样的:
Try setting the TextRenderingHint
property of your Graphics
object to AntiAlias
尝试将
Graphics
对象的TextRenderingHint
属性设置为AntiAlias
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx http://msdn.microsoft.com/en-us/library/system.drawing.graphics.textrenderinghint.aspx
You can try a few things: 你可以尝试一些事情:
In your XAML: 在你的XAML中:
TextOptions.TextFormattingMode="Display" (and other TextOptions attached properties) TextOptions.TextFormattingMode =“显示”(和其他TextOptions附加属性)
In your C#: 在你的C#中:
TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display); TextOptions.SetTextFormattingMode(this,TextFormattingMode.Display);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.