Search code examples
c#.netcompact-framework

Center aligining text in compact framework?


I'm trying to draw a custom button in compact framework, in the 'OnPaint' function I do something like this:

protected override void OnPaint(PaintEventArgs e)
{
    System.Drawing.Imaging.ImageAttributes a = new    
    System.Drawing.Imaging.ImageAttributes();
    e.Graphics.DrawImage(pictureBox1.Image, new Rectangle(0, 0, Width, Height),  
                         0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, a);

    Brush b = new SolidBrush(Color.Black);
    e.Graphics.DrawString(Text, Font, b, 0, 0, ( 
                     new StringFormat(StringFormatFlags.NoWrap)));
}

With this code the font draws in the top left corner of the control (as expected).

My question is, how can I get it to draw centre on the control?


Solution

  • Figured it out!

    For those interested,

    float fontHeight = e.Graphics.MeasureString("ABC", Font).Height;
    e.Graphics.DrawString("ABC", Font, b, new RectangleF(0, Height / 2.0f - fontHeight/2.0f, Width, Height), format);
    

    Did it for me.