在中心绘制文字

Pri*_*his 11 c# forms

哪个是在rectangleF的中心drawString的最佳方法?可以减小文本字体大小以适应它.在大多数情况下,Text太大而不适合给定的字体,因此必须减少字体.

tek*_*ues 16

此代码水平和垂直居中文本:

stringFormat sf;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
grp.DrawString(text, font, Brushes.Black, rectf, sf);
Run Code Online (Sandbox Code Playgroud)


Fre*_*örk 11

我打得四处它了一下,发现这个解决方案(假设RectangleF rectstring text已定义):

StringFormat stringFormat = new StringFormat()
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center
};

using (Graphics g = this.CreateGraphics())
{
    SizeF s = g.MeasureString(text, this.Font);
    float fontScale = Math.Max(s.Width / rect.Width, s.Height / rect.Height);
    using (Font font = new Font(this.Font.FontFamily, this.Font.SizeInPoints / fontScale, GraphicsUnit.Point))
    {
        g.DrawString(text, font, Brushes.Black, rect, stringFormat);
    }
}
Run Code Online (Sandbox Code Playgroud)


Pri*_*his 4

我知道它对我有用。这就是我所做的

Size textSize = TextRenderer.MeasureText(Text, Font);
float presentFontSize = Font.Size;
Font newFont = new Font(Font.FontFamily, presentFontSize, Font.Style);
while ((textSize.Width>textBoundary.Width || textSize.Height > textBoundary.Height) && presentFontSize-0.2F>0)
{
   presentFontSize -= 0.2F;
   newFont = new Font(Font.FontFamily,presentFontSize,Font.Style);
   textSize = TextRenderer.MeasureText(ButtonText, newFont);
}
stringFormat sf;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(Text,newFont,Brushes.Black,textBoundary, sf);   
Run Code Online (Sandbox Code Playgroud)