Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw text at center

Tags:

c#

forms

Which is the best way to drawString at the center of a rectangleF? Text font size can be reduced to fit it. In most case the Text is too big to fit with a given font so have to reduce the font.

like image 283
Prithis Avatar asked Jun 09 '09 14:06

Prithis


People also ask

How do I center text in canvas?

textAlign = "center"; Which should put a text centered both vertically and horizontally.

How do you center text in JavaScript?

To center text in JavaScript, do this: element. style. textAlign = 'center' .


1 Answers

I played around with it a bit and found this solution (assuming that the RectangleF rect and string text are already defined):

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);
    }
}
like image 119
Fredrik Mörk Avatar answered Oct 13 '22 01:10

Fredrik Mörk