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

sz81bmfz  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(227)

我有一个显示图像的自定义控件。图像周围有一个框架,每个角有4个大小手柄。如果用户将光标移动到大小手柄,他应该能够调整图像的大小,保持纵横比。
我已经有了一个有效的resize方法:

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是否发生了变化,并根据变化的值确定了resize的值。
是否有更好的方法来获得正确的xy增量,并根据正在移动的夹点来调整图像的大小以保持纵横比?

mwngjboj

mwngjboj1#

请尝试以下方法。创建具有可缩放样式的自定义控件。

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

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

            return cp;
        }
    }
}

将其放置在窗体上,设置layout属性。当设置为Zoom时,纵横比将保持不变。

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

准备好了!用户可以用鼠标更改控件的大小。图像尺寸将自动更改。

quhf5bfb

quhf5bfb2#

你似乎把日常工作搞得太复杂了,解决的方法应该很简单:
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监视。

相关问题