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 rect和string 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)
我知道它对我有用。这就是我所做的
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)
| 归档时间: |
|
| 查看次数: |
15013 次 |
| 最近记录: |