Search code examples
c#system.drawing

Draw rectangle box for letters


My code. Output: enter image description here

Bitmap bitmap = new Bitmap(600, 300, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
GraphicsPath path = new GraphicsPath();
StringFormat format = new StringFormat();
Rectangle rect = new Rectangle(0, 0, 600, 300);
SolidBrush Brush = new SolidBrush(Color.White);
g.FillRectangle(Brush, rect);


g.SmoothingMode = SmoothingMode.AntiAlias;
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
path.AddString(textBox1.Text, FontFamily.GenericSansSerif, (int)FontStyle.Bold, 128, rect, format);

Brush = new SolidBrush(Color.Blue);
g.FillPath(Brush, path);

float x = path.GetBounds().X;
float y = path.GetBounds().Y;
float w = path.GetBounds().Width / textBox1.Text.Length;
float h = path.GetBounds().Height;

Pen redPen = new Pen(Color.Red, 2);
for (int i = 0; i < textBox1.Text.Length+1; i++)
{
    rect = new Rectangle((int)x, (int)y, (int)w*i, (int)h);
    g.DrawRectangle(redPen, rect);
}

pictureBox1.Image = bitmap;

I am getting the wrong result in the output because I cannot get the corners of the letters and am using the wrong way.

But i need get correct pixels of letter corners, draw rectangle and fill it. Like this: enter image description here


Solution

  • This line made me find one error in your code:

    for (int i = 0; i < textBox1.Text.Length+1; i++)
    

    It should be:

    for (int i = 0; i < textBox1.Text.Length; i++)
    

    But then indeed only 3 red boxes seem to appear.

    The reason for that is the first rectangle (with your code) is very small, because the width is (int)w*i. That should be (int)w*(i+1).

    Now back to the place where you are drawing rectangles.

    If you take the text 'WWWW', you will see that your solution seems pretty OK.

    But if you test with 'IIII', ten you should note that the left-most 'I' is left aligned in the red box, and the right-most 'I' is right aligned in the red box.

    You are drawing 4 equal boxes round 4 letters with different with.

    A solution could be to draw the letters with a monospaced font.

    or, if you do not want a monospaced font, look at How to measure width of character precisely?