繁体   English   中英

如何在Graphics DrawString中更改文本字体大小?

[英]How can i change in Graphics DrawString the text font size?

我正在使用此方法在form1上绘制文本:

private bool DrawText(bool draw, string texttodraw)
        {
            Graphics g = this.CreateGraphics();
            SizeF size = g.MeasureString(texttodraw, SystemFonts.DefaultFont,14);
            g.DrawString(texttodraw, Font, Brushes.Red, pictureBox1.Location.X + (pictureBox1.Width / 2) - (size.Width / 2),
                                                                    pictureBox1.Location.Y - 30);
            return draw;
        }

我试图在SizeF size lline上将Width设置为14,但是它并没有改变昏暗感,唯一要做的就是将文本从其位置移开一点。

如何更改文本的字体大小,并保持文本位置的透视图(如果这是正确的词)?

这就是当根本不使用宽度14时,文本位于pictureBox1上方的中间的样子。 我希望当我更改文字大小时,它会像现在一样保持在中间。

文本为红色,在这种情况下为希伯来语。

文本

尝试使用更大的字体:

using (Font bigFont = new Font(SystemFonts.DefaultFont.FontFamily, 14, FontStyle.Regular)) {
  SizeF size = g.MeasureString(texttodraw, bigFont, 14);
  g.DrawString(texttodraw, bigFont, Brushes.Red, pictureBox1.Location.X + (pictureBox1.Width / 2) - (size.Width / 2),
                                                          pictureBox1.Location.Y - 30);
}

请避免使用CreateGraphics,它只是一个临时图形,会因重叠窗口或最小化表单而被擦除。 也会引起闪烁。 使用paint事件中的图形对象并使控件无效以更新绘画。

此外,请务必在文本渲染中使用TextRenderer.DrawText和TextRenderer.MeasureText。 DrawString应该主要用于打印到纸张上。

我认为最好的方法是使用Graphics.DrawString()函数的第5次重载使用StringFormat对象将文本水平或垂直居中对齐或同时对齐:

在此处输入图片说明

您需要提供一个Rectangle对象,并已针对该对象进行对齐。

StringFormat sf=new StringFormat();
sf.LineAlignment = StringAlignment.Center;//center-align vertically
sf.Alignment = StringAlignment.Center; //center-align horizontally
     private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        Font drawFont = new Font("Arial Black", 9);
        e.Graphics.DrawString(nic.Text, drawFont, Brushes.Maroon, 174, 12);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM