调整矩形大小并对齐到固定比例 [英] Resizing a rectangle and snapping to a fixed ratio

查看:91
本文介绍了调整矩形大小并对齐到固定比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前拥有一些代码,当用户单击与以下区域相对应的多个锚点时,该代码会根据鼠标的移动来调整矩形的大小:左,上,右,下,TopLeft,TopRight,BottomLeft,BottomRight.

I currently have code which resizes a rectangle based on mouse movement when the user clicks on multiple anchors which correspond to the following areas: Left, Top, Right, Bottom, TopLeft, TopRight, BottomLeft, BottomRight.

因此,用户可以单击并拖动顶部锚点,它将根据鼠标的位置调整矩形的顶部坐标.其他所有锚点都一样.

So the user can click and drag the top anchor and it will adjust the Top coordinate of the rectangle based on where the mouse is. Same for all the other anchors.

事实上,我想通过基于动作捕捉矩形的适当边来强制执行固定比例(例如2:3或5:7).我已经为Left,Top,Right和Bottom锚完成了此操作,因为这很容易,如果我要调整宽度的大小,我只需要根据比率自动调整高度,反之亦然.

After the fact I want to enforce a fixed ratio (such as 2:3 or 5:7) by snapping the appropriate sides of the rectangle based on the action. I have done this for the Left, Top, Right, and Bottom anchors because it's easy, if I'm resizing the width I just need to auto-size the height based on the ratio, and vice-versa.

我遇到的困难是用户拖动诸如右下角或左上角锚点之类的角时.我需要弄清楚如何选择要捕捉的那一侧.我有鼠标坐标以及矩形的左,上,右和下.

The difficulty I'm having is when the user is dragging a corner such as the Bottom Right or the Top Left anchor. I need to figure out how to choose which side to snap. I have the mouse coordinate and the left, top, right, and bottom of the rectangle.

这是我尝试过的代码:

case Anchor.BottomRight:
    float maxRight = CursorPosition.X;
    float maxBottom = CursorPosition.Y;

    float newRight = Bounds.Left + (Bounds.Width * widthRatio);
    float newBottom = Bounds.Top + (Bounds.Height * heightRatio);

    if (newRight < maxRight)
    {
        Width = Height * widthRatio;
    }
    else
    {
        Height = Width * heightRatio;
    }

    break;

在固定比例为2:3的示例中,widthRatio为0.666,heightRatio为1.5.

In an example of a fixed ratio of 2:3 the widthRatio would be 0.666 and the heightRatio would be 1.5.

此代码有一半的时间可以工作,但是当然基本上有50/50的工作机会.我必须确定适当的条件来捕捉宽度或高度.

This code works half of the time but of course it's basically a 50/50 chance of working. I have to identify a proper condition to snap either the width or the height.

推荐答案

我知道了.

if (Height * widthRatio <= Width)
    Width = Height * widthRatio;
else if (Width * heightRatio <= Height)
    Height = Width * heightRatio;

这将以固定比例模拟Photoshop中的功能.

This will emulate the functionality in Photoshop with a Fixed Ratio.

这篇关于调整矩形大小并对齐到固定比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆