Centering an individual character with DrawString

后端 未结 3 1975
离开以前
离开以前 2021-01-13 08:04

I have tried all of the suggested ways to center text, but I can\'t seem to get the results I want while centering an individual character.

I have a rectangle. In t

3条回答
  •  梦谈多话
    2021-01-13 08:33

    Though John Arlen's answer is perfect, I'd like to post my answer:

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
             // Set up string.
            string measureString = "HelloWorld";
            Font stringFont = new Font("Arial", 100, FontStyle.Regular, GraphicsUnit.Pixel);
    
            // Measure string.
            SizeF stringSize = new SizeF();
            stringSize = e.Graphics.MeasureString(measureString, stringFont);
    
            // Draw rectangle representing size of string.
            e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 10.0F, 10.0F, stringSize.Width, stringSize.Height);
    
            // Draw string to screen.
            e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(10, 10f + stringSize.Height / 12.0f));
        }
    

    code result like that: result in my computer

    "HelloWorld" is centered vertically in the red box.

    For the height of descender line is approximately equal 1/6 of stringSize.Height calculated by MeasureString


    | top padding 1/6

    | word body 3/6

    | word descender 1/6

    | bottom padding 1/6

提交回复
热议问题