Prithis
Prithis

Reputation: 1033

Draw text at center

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.

Upvotes: 11

Views: 17622

Answers (6)

Yas
Yas

Reputation: 5471

Easy to use :)

    public static void DrawStringCenter(Image image, string s, Font font, Color color, RectangleF layoutRectangle)
    {
        var graphics = Graphics.FromImage(image);

        var brush = new SolidBrush(color);

        var format = new StringFormat
        {
            Alignment = StringAlignment.Center,
            LineAlignment = StringAlignment.Center
        };

        graphics.DrawString(s, font, brush, layoutRectangle, format);
    }

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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

Upvotes: 11

Prithis
Prithis

Reputation: 1033

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

Upvotes: 4

tekBlues
tekBlues

Reputation: 5793

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

Upvotes: 16

Serapth
Serapth

Reputation: 7162

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.

Upvotes: 0

Lazarus
Lazarus

Reputation: 43074

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.

Upvotes: 0

Related Questions