简体   繁体   中英

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

I'm using this method to draw the text on 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;
        }

I tried to set Width to 14 on the SizeF size lline but it didn't change the dize and the only thing it did is moving a bit the text from it's location .

How can i change the font size of the text, and also to keep the perspective(if this is the right word to use) of the text location ?

This is how it look like when not using the Width 14 at all the text is in the center above the pictureBox1. I want that when i change the text size it will be kept to be in the center like it is now.

The text is in Red and it's in hebrew in this case.

文本

Try using a bigger font:

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);
}

Do avoid using CreateGraphics, it's only a temporary drawing that will get erased by overlapping windows or minimizing the form. It will also cause flicker. Use the graphics object from the paint event and invalidate the control to update the painting.

Also, do favor using TextRenderer.DrawText and TextRenderer.MeasureText for your text renderings. DrawString should primarily be used for printing to paper.

I think the best way is to use StringFormat object to center-align the text either horizontally or vertically or both using the 5th overload of Graphics.DrawString() funciton:

在此处输入图片说明

You need to provide a Rectangle objet and alignment is done with respect to this object.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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