Daniel Bout
Daniel Bout

Reputation: 143

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.

Text

Upvotes: 0

Views: 12174

Answers (3)

Omid Sadeghi
Omid Sadeghi

Reputation: 694

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:

enter image description here

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

Upvotes: 1

HarleyD
HarleyD

Reputation: 1

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

Upvotes: 0

LarsTech
LarsTech

Reputation: 81610

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.

Upvotes: 5

Related Questions