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.
textAlign = "center"; Which should put a text centered both vertically and horizontally.
To center text in JavaScript, do this: element. style. textAlign = 'center' .
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With