Search code examples
c#imagesizepicturebox

Grow picturebox to top direction


Is it possible to give a picturebox a new size but instead of it growing down and right i want it to grow up and right. So basicaly I want the left bottom corner to be locked in the same position all the time.

As you can see in the image i want the green box to be above the line. I have tried to make a formula to calculate the new position but cant figure out how to write it.


Solution

  • If you're assigning size at runtime, for example:

    private void button1_Click(object sender, EventArgs e)
    {
        this.pictureBox1.Size = new Size( 200, 200 );
    }
    

    then just handle the PictureBox Resize event:

    private void pictureBox1_Resize(object sender, EventArgs e)
    {
        var padding = 12; //Forms designer snap-to padding.
        var titleBarHeight = 41;
    
        this.pictureBox1.Location = new Point(padding, this.Height - this.pictureBox1.Height - titleBarHeight - padding);
    }
    

    This will handle the size assignment, as well as if you've anchored the PictureBox and are resizing the form.

    If you're just resizing at design time, then just anchor the PictureBox:

    enter image description here

    It'll resize where ever it's sitting on the form. As mentioned above, it'll also work automatically for form resize at run time.