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.
A:
Determine the size of the text to be drawn and then determine the offset for the start of the string from the centre of rectangleF and draw it.
Lazarus
2009-06-09 14:42:41
A:
Get width/2 and height/2 of the rectangle, then using System.Graphics.MeasureString to get the dimensions of your string, again half them and subtract from your earlier width/height values and you end up with the X,Y coordinate to draw your string at in order for it to be centered.
Serapth
2009-06-09 14:44:27
+3
A:
This code centers the text horizontally and vertically:
stringFormat sf;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
grp.DrawString(text, font, Brushes.Black, rectf, sf);
tekBlues
2009-06-09 14:45:13
what about reducing the font size?
Prithis
2009-06-09 14:52:49
A:
It is working for me know. This is what I did
Size textSize = TextRenderer.MeasureText(Text, Font);
float presentFontSize = Font.Size;
Font newFont = new Font(Font.FontFamily, presentFontSize, Font.Style);
while ((textSize.Width>textBoundary.Width || textSize.Height > textBoundary.Height) && presentFontSize-0.2F>0)
{
presentFontSize -= 0.2F;
newFont = new Font(Font.FontFamily,presentFontSize,Font.Style);
textSize = TextRenderer.MeasureText(ButtonText, newFont);
}
stringFormat sf;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(Text,newFont,Brushes.Black,textBoundary, sf);
Prithis
2009-06-09 15:07:45
I saw that you had posted your working solution when I posted my version, but I let mine stay since it is more efficient (gets the font size without looping) and also I think that your code might leak memory, creating many font objects but not calling Dispose on them.
Fredrik Mörk
2009-06-09 15:22:53
A:
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);
}
}
Fredrik Mörk
2009-06-09 15:12:22