Lionel
Lionel

Reputation: 152

C# - Resize Bitmap from a variable String

In my application, I generate a Bitmap with a variable string.

Here is my function:

public void Image(String text, String font, int size)
{    
    Font font = new Font(font, size);
    float res = ((font.SizeInPoints * text.Length) / 72) * 96;

    using (Bitmap img = new Bitmap((int)res, font.Height))
    {
        Graphics g = Graphics.FromImage(img);

        SolidBrush drawBrush = new SolidBrush(Color.Black);

        g.DrawString(text, font, drawBrush, 1, 0);

        String directory = AppDomain.CurrentDomain.BaseDirectory + "Content\\Images\\Signature\\";
        string outputFileName = directory + "sign.png";

        img.Save(outputFileName, ImageFormat.Png);
    }
}

I would like the width of the image to match perfectly the width of the string printed in that bitmap.

As you can see, I tried to calculate the width with point size of the font.
The problem is that each letter printed has a different width so I can not get the size before creating the Bitmap.

Plus, I don't even know how to retrieve the actual size of the printed string...

Does anyone have an idea?

Upvotes: 0

Views: 428

Answers (1)

Bradley Uffner
Bradley Uffner

Reputation: 17001

Use the Graphics.MeasureString function. It takes a string and a font, and returns the size of the rendered text as a SizeF. There are also additional overloads that can take formatting information, and one that takes a SizeF representing the maximum width for wrapping.

Details can be found here: https://msdn.microsoft.com/en-us/library/6xe5hazb(v=vs.110).aspx

// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);

// Set maximum layout size.
SizeF layoutSize = new SizeF(100.0F, 200.0F);

// Set string format.
StringFormat newStringFormat = new StringFormat();
newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical;

// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, layoutSize, newStringFormat);

// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);

// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 

Upvotes: 1

Related Questions