在.NETCF(Windows Mobile)中 如何水平居中显示字符串?
解决方案
调整字体大小:
private void DrawLetter()
{
Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width);
float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font);
g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
{
//计算实际尺寸,根据需要缩小
while (true)
{
SizeF size = g.MeasureString(text, font);
//如果适合,则退出
if (size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
//尝试使用较小的字体(旧字体的 90%)
Font oldFont = font;
font = new Font(font.Name, (float)(font.Size * .9), font.Style);
oldFont.Dispose();
}
}
还可以使用StringFormat对象对齐文本:
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
e.Graphics.DrawString("My String", this.Font, Brushes.Black, ClientRectangle, format);
日期:2020-07-08 08:36:51 来源:oir作者:oir
