0

我有一个由 R1:x1,y1-x2,y2 定义的矩形,在应用缩放后,我得到了矩形 R2:X1,Y1-X2,Y2。

+--------------+---+
|              |   |
|     R1       |   |
|              |   |
+--------------+   |
|              R2  |
+------------------+

如您所见,R2 基于 R1 的原点进行了扩展。不是我想要的效果。

我想要完成的是根据执行缩放操作时鼠标指针的位置重新计算原点。

例如:

   +-----------------------+ 
   | +-----------------+   |
   | |  o              |   |
   | |       R1        |   |
   | |                 |   |
   | +-----------------+   |
   |            R2         |
   +-----------------------+

在这里,鼠标指针被设置在点“o”上,然后缩放,得到一个矩形 R2。请注意,R2 不是以 R1 为中心,而是稍微向右和底部偏移。

缩放后如何重新定位原点?

4

1 回答 1

2

This isn't a programming specific question, but a math problem.

If the mouse is in the center of the screen, each side expands equally. If the mouse is all the way to one side, the rectangle expands only in that direction. So you need to determine the size increase from a ratio.

So, we need to setup a few variables here: width_delta, height_delta, mouse_x_relative, mouse_y_relative, rect_width, rect_height.

  • Width delta is the new width minus the old width.
  • Height delta is the new height minus the old height.
  • Mouse x relative is the x-coordinate relative to the rect's left side
  • Mouse y relative is the y-coordinate relative to the rect's top side

With each delta, when the mouse is perfectly centered, we can calculate the change in the rectangles sides with delta - delta / 2, and delta / 2. This results in half of the delta going to the one side, the other half to the other. So instead of dividing by 2, we need to find out how this relates to the mouse position and the size of the rect.

Easy enough: rect_width / mouse_x_relative. Let's say a rect is width 10, mouse is in the center at 5, 10 / 5 is 2, causing the delta to be distributed equally to both sides of the rect. So we need to divide the delta by rect_width / mouse_x_relative.

left_delta = width_delta / rect_width / mouse_x_relative
right_delta = width_delta - left_delta 

But we can clean that up to be:

left_delta = width_delta * mouse_x_relative / rect_width
right_delta = width_delta - left_delta 

I believe that should work with your expected behavior, unlike my last answer. When you zoom in (shrink) the rect closes in on the mouse (centering), when you zoom out it moves away from the mouse (un-centering, if you will), the inverse of the way it moved in.

于 2013-05-03T01:01:05.353 回答