Chris
Chris

Reputation: 11

Resize a PictureBox in the middle

I need your help today to resize a PictureBox in WinForms while keeping it in the middle.
What really happened is that the PictureBox became bigger and bigger to the Left and Down directions!

Here is my code:

public partial class Form1:Form
{
    private int x = 25;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        x++;
        pictureBox1.Size = new Size(x,x);
    }
}

Note:
I have tried changing the Anchor property - as I read similar articles - to everything (None, all directions...). But nothing changed!

Also, I have tried changing its location every time I change its size, but that was not a smooth move to look at!

Upvotes: 1

Views: 197

Answers (2)

Sam
Sam

Reputation: 43

Use code below after changing pictureBox1's size

int righty = this.Width - (pictureBox1.Location.X + pictureBox1.Width);
int downy = this.Height - (pictureBox1.Location.Y + pictureBox1.Height);
pictureBox1.Top = (downy + pictureBox1.Top) / 2;
pictureBox1.Left = (righty + pictureBox1.Left) / 2;

i'm using it in my WinForm app and it's working . it keeps the balance of four edges of pictureBox1 between four edges of form and keeps pictureBox1 in the middle .

Upvotes: 1

Jimi
Jimi

Reputation: 32248

See if this progressive resizing is smooth enough.
The PictureBox will expand maintaining it's initial center position.
The Timer is set with an .Interval = 100. Each Timer.Tick(), the size of the PictureBox is increased by an amount (2 pixels, in this case).

The PictureBox.Location value is decreased by half of that amount.
Play with it until you find speed and size values you're comfortable with.

public partial class Form1 : Form
{
    private int PictureBoxResize = 2;

    public Form1()
    {
        InitializeComponent();
        timer1.Tick += new EventHandler(this.timer1_Tick);
        timer1.Interval = 100;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Location = new Point(pictureBox1.Left - (PictureBoxResize / 2), 
                                         pictureBox1.Top - (PictureBoxResize / 2));
        pictureBox1.Size = new Size(pictureBox1.Width + PictureBoxResize, 
                                    pictureBox1.Height + PictureBoxResize);
    }
}

Upvotes: 1

Related Questions