缩放动画(使用鼠标事件调整图像大小)

时间:2014-05-27 10:15:52

标签: c# winforms animation resize zoom

当我使用winforms在c#中选择图像时,我正在尝试实现一个简单的动画。 目标是当用户用鼠标(mouse_down)触摸其中一个缩小的图像时,它会调整大小(长大)并传递一些原始大小(原始大小大于起始大小),并且下一瞬间,它恢复到原来的大小。

我在使用c#的动画中非常新,所以,任何形式的帮助都会很好:)

我尝试实施的代码如下:

// - Grows up the control to a bigger size than the original one
            while ((sender as Peça).Width < (sender as Peça).imagem.Width)
            {
                (sender as Peça).Width = (int)((sender as Peça).Width * 1.8);
                (sender as Peça).Height = (int)((sender as Peça).Height * 1.8);
                (sender as Peça).setSize(new Size((sender as Peça).Width, (sender as Peça).Height));
                Application.DoEvents();
            }

            // - Return the size of the control to the original one
            if ((sender as Peça).Width > (sender as Peça).imagem.Width)
            {
                (sender as Peça).Width = (sender as Peça).imagem.Width;
                (sender as Peça).Height = (sender as Peça).imagem.Height;
                (sender as Peça).setSize(new Size((sender as Peça).Width, (sender as Peça).Height));
            }

但我没有得到我想要的结果,动画不顺畅,因此我认为不是最正确的。

我知道winforms并不是最好的,但我必须利用这段时间。是否有winforms的动画库?

非常感谢提前

1 个答案:

答案 0 :(得分:2)

是的,对于简单动画,您使用Timer。如果有的话,任何其他方式都不会顺利进行。

这是一个使图片框更大(10像素)并恢复到mousedown和mouseUp上的原始大小的示例。

我已将Timer设置为10毫秒的Interval,这比它的实际分辨率小一点。 15毫秒,所以它会像它一样平滑。

注意:我增加了2个像素,因此我可以将位置调整为1,而Picturebox不会移动。其SizeModeZoom

你可以扩展它,如果你希望它缩小到原来然后最终重置,但这应该让你去..:

Size originalSize;   //**
Point originalLoc;   //**
int resize = 0;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    originalSize = pictureBox1.Size;   //**
    originalLoc= pictureBox1.Location;
    resize = 1;
    timer1.Interval = 10;
    timer1.Start();
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    resize = -1;
    timer1.Start();
}

private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
    timer1.Stop();
    pictureBox1.Size = originalSize;
    pictureBox1.Location = originalLoc;
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (resize > 0 && pictureBox1.Width < originalSize.Width+ 10)     //**
    {
        pictureBox1.Size = new Size(pictureBox1.Width + 2, pictureBox1.Height + 2);
        pictureBox1.Location = new Point(pictureBox1.Left - 1, pictureBox1.Top - 1);
    }
    else if (resize < 0 && pictureBox1.Width > originalSize.Width)    //**
    {
        pictureBox1.Size = new Size(pictureBox1.Width - 2, pictureBox1.Height - 2);
        pictureBox1.Location = new Point(pictureBox1.Left + 1, pictureBox1.Top + 1);
    }
    else timer1.Stop();
}

注2:我做了一些更改(**),即使在mousedown离开时也能可靠地重置。