使用鼠标调整图像大小并保持纵横比

时间:2016-06-20 09:37:13

标签: c# winforms gdi+

我有一个显示图像的自定义控件。图像周围有一个框架,每个角落有4个尺寸的把手。如果用户将光标移动到大小夹点,他应该能够保持纵横比的大小。

我已经有一个有效的调整大小方法:

public void Resize(float value)
{
    if (value == 0f)
        value = 0.05f;

    //Resize by the same value to keep aspect ratio
    var width = (int)(frame.Width * value);
    var height = (int)(frame.Height * value);

    //Image resizing removed...
}

Resize方法本身正在起作用,因为我可以将任何值传递给它并保持纵横比。 widthheight都会使用相同的值调整大小。

问题是通过移动其中一个尺寸夹具进行尺寸调整不能按预期工作。此外,图像失去其纵横比。在MouseMove事件中,我有:

if (e.Button == MouseButtons.Left)
{
    //Get mouse position delta
    var x = mousePosition.X - e.Location.X;
    var y = mousePosition.Y - e.Location.Y;

    if (x == 0 && y == 0)
        return;

    bool doY = false;
    var diff = x;

    if (x == 0 && y != 0)
    {
        diff = y;
        doY = true;
    }

    float width = frame.Width + diff;
    float amount = frame.Width / width;

    if (doY)
    {
        float height = frame.Height + diff;
        amount = frame.Height / height;
    }

    Resize(amount);
}

通过移动鼠标光标尝试调整大小时,不会考虑宽高比。在上面的代码中,我确定xy是否有更改,并且根据更改的值,我确定调整大小值。

是否有更好的方法来获得正确的xy增量,并根据要移动的手柄,调整图像大小以保持纵横比?

2 个答案:

答案 0 :(得分:0)

你似乎过于复杂的例程。对此的处理方法应该是简单的:

Store the initial size of your control on load.

On resize, compare the new size of the control and choose the most significant dimension change - width or height - base on some logic, e.g. the biggest one.

Calculate the ratio by which the dimension is changed, by comparing its new amount to the stored one.

Then apply this ratio by changing the other dimension in code.

Finally store the new size for future reference.

应该这样做。不需要进行Mouse_Move监控。

答案 1 :(得分:0)

尝试以下方法。创建具有相当大样式的自定义控件。

class SizeablePictureBox : PictureBox
{
    protected override CreateParams CreateParams
    {
        get
        {
            const int WS_SIZEBOX = 0x40000;

            var cp = base.CreateParams;
            cp.Style |= WS_SIZEBOX;

            return cp;
        }
    }
}

将其放在表单上,​​设置布局属性。设置为Zoom时,宽高比将保持不变。

var pictureBox = new SizeablePictureBox { Parent = this, Width = 500, Height = 500 };
pictureBox.BackgroundImageLayout = ImageLayout.Zoom;
pictureBox.BackgroundImage = Image.FromFile("pic.jpg");

就绪!用户可以使用鼠标更改控件的大小。图像尺寸将自动更改。