C# resize picturebox generated image

439 views Asked by At

I draw an image based on text (_label)

public Image getImage()
    {

        PointF initialLocation = new PointF(0.1f, 0.1f);
        //Bitmap b = new Bitmap(130, 50);

        Graphics g = Graphics.FromImage(new Bitmap(1,1));
        System.Drawing.Font font = new System.Drawing.Font("Arial", 16, FontStyle.Regular);
        SizeF bounds = g.MeasureString(_label, font, new PointF(0,0), new StringFormat(StringFormatFlags.MeasureTrailingSpaces));

        Bitmap b = new Bitmap((int)bounds.Width, (int)bounds.Height);

        //b.MakeTransparent();
        using (Graphics graphics = Graphics.FromImage(b))
        {
            //using (Font arialFont = new Font("Arial", 16))
            {
                graphics.DrawString(_label, font, Brushes.White, initialLocation);
            }
        }

        Image image = b;
        return image;
    }

This draws an image to the size of how long the text would take. For example "LabelTest" in this case would be Image.Width = 103 and Image.Height = 26. I also want to be able to update (set) the text and update it on the screen. When I change the text to "LabelTest123456789" and call the getImage() method again, the Image.Width changes to 213.

In the parent class I then set the PictureBox Image mentioned above:

public partial class Widget : System.Windows.Forms.PictureBox

.. .. ..

else if (t == Widget.WidgetType.LABEL)
        {

            **base.Image = image;**
            base.BackColor = Color.Transparent;
        }

An onPaint method is then called to draw it on the screen:

protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }

In this 'onPaint' method, the value for ClipRectangle still has the properties of the size from when it was first set (103,26), I expected this to use the new size (213,26).

The objective is to make an image based on a string of text, I also want to be able to update the string and redraw the updated string.

Many thanks in advance!

1

There are 1 answers

0
David Evans On

Setting the new size of the image has solved my problem.

base.Image = newImage; //old image size(100,20) - newImage size(150, 20)
base.Size = new Size(newImage.Width, newImage.Height);
base.Refresh(); //forces redraw