tags:

views:

157

answers:

5

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
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
+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
what about reducing the font size?
Prithis
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
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
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