简体   繁体   中英

How can I change PictureBox size incrementally and smoothly ? ( in winforms , c# , visual studio 2013 )

I have a Button in my form and a PictureBox with width 290 and height 145 that is hidden at first . I want to show the PictureBox little by little while the button's MouseEnter event happens . So I tried this code :

private void button1_MouseEnter(object sender, EventArgs e)
{
    pictureBox1.Size = new Size(0, 145);
    pictureBox1.Show();
    for (int i = 0; i < 290; i++)
        pictureBox1.Size = new Size(i, 145);
}

But it shows the PictureBox immediately with the primary size .

I found a similar question in this site ( PictureBox does not change its size ) , but actually its answers couldn't help me , too .

Your code executes all at once, so all you will see is a sudden change.

Use a timer and gradually increase the size when the timer ticks.

timer = new Timer(16); //~60 FPS
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

...

private void button1_MouseEnter(object sender, EventArgs e)
{
    pictureBox1.Size = new Size(0, 145);
    pictureBox1.Show();

    timer.Enabled = true; // Enable it
}

...

private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (pictureBox1.Width < 290)
        pictureBox1.Width++; //Increment
    else
        timer.Enabled = false; //Disable
}

You must use the Update method of your pictureBox in order to redraw it. Also a little delay will change the size more smoothly on Faster computers.

I changed your code like this:

private void button1_MouseEnter(object sender, EventArgs e)
{
    pictureBox1.Size = new Size(145, 145);            
    for (int i = 145; i < 290; i++)
    {
        pictureBox1.Size = new Size(i, i);
        pictureBox1.Update();
        System.Threading.Thread.Sleep(1);
    }
}

1) define a new int as public :

public partial class Form1 : Form
    {
        int counter = 0;
.
.
.

2) use a timer :

 private void timer1_Tick(object sender, EventArgs e)
        {
            counter = counter + 10;
            timer1.Interval = 10;
            pictureBox1.Show();
            if (counter <= 290)
            { pictureBox1.Width += 1; }            
        }

3) enable the timer in mouse event:

private void button1_MouseEnter(object sender, EventArgs e)
{
    counter = 0;
    pictureBox1.Width = 0;
    timer1.Enabled = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM