繁体   English   中英

优雅的方式来定位两个矩形

[英]Elegant way to position two rectangles

我有一个矩形(称为目标 ),并希望在旁边放置另一个矩形(称为卫星 )。 卫星具有一个位置 (顶部,底部,左侧,右侧),用于确定相对于目标的放置边缘。 它还有一个对齐方式 (左侧,中间,右侧为顶部和底部位置,顶部,中间和底部为左侧和右侧位置)。

例:

+----------+----------------------------+
|          |                            |
|  Target  | Satellite, Position=RIGHT, |
|          | Align=TOP                  |
|          |                            |
|          |----------------------------+
|          |
+----------+

我知道目标的左上角坐标以及它的宽度和高度 我也知道卫星的宽度和高度,并想要计算它的左上角坐标。 我可以将其作为一系列12 if子句,但也许有更优雅,数学或算法的方法来做到这一点。 还有另一种方法:

# s = satellite, t = target
if pos == "top" && align == "left"
  s.x = t.x
  s.y = t.y - s.height
else if pos == "top" && align == "center"
  s.x = t.x + t.width / 2 - s.width / 2
  s.y = t.y - s.height
# etc, etc

Ruby或JavaScript中的任何好的解决方案?

我喜欢另一个答案,但这里是如何做到这一点,而不必存储任何东西。 所有数学和逻辑使用javascript true的技巧评估为1,并且当应用算术运算符时, false计算结果为0:

ps(查看工作jsfiddle: http//jsfiddle.net/vQqSe/52/

var t = {
    jq: $('#target'),
    width: parseInt($('#target').css('width')),
    height: parseInt($('#target').css('height')),
    top: parseInt($('#target').css('top')),
    left: parseInt($('#target').css('left'))
};
var s = {
    jq: $('#satellite'),
    width: parseInt($('#satellite').css('width')),
    height: parseInt($('#satellite').css('height'))
};

// start with it top left and add using javascript tricks
s.jq.css('top', t.top - s.height +
    s.height * (a == 'top') +
    (t.height/2 + s.height/2) * (a == 'middle') +
    t.height * (a == 'bottom') +
    (t.height + s.height) * (p == 'bottom')
);        

s.jq.css('left', t.left - s.width +
    t.width * (a == 'left') +
    s.width * (a == 'right') +
    (s.width/2 + t.width/2) * (a == 'center') +
    (s.width + t.width) * (p == 'right')
);

如果您使用了一系列对象,它将起到作用:

var positions = {

    top: {left:{x:t.x, y:y.y-s.height}, center:{x:tx.x + t.width/2- s.width/2, y:t.y-s.height}}
    //etc....
}
//then to get the position you can simply
var pos = positions[pos][align])
def vector pos, align, hash
  case hash[pos]
  when -1;     [0.0, -1.0]
  when 1;      [1.0, 0.0]
  else
    case hash[align]
    when -1;   [0.0, 0.0]
    when 1;    [1.0, -1.0]
    else       [0.5, -0.5]
    end
  end
end

y_t, y_s = vector(pos, align, "top" => -1, "bottom" => 1)
x_t, x_s = vector(pos, align, "left" => -1, "right" => 1)
s.y = t.y + y_t*t.height + y_s*s.height
s.x = t.x + x_t*t.width + x_s*s.width

要么

def vector pos, align, head, tail
  case pos
  when head;   [0.0, -1.0]
  when tail;   [1.0, 0.0]
  else
    case align
    when head; [0.0, 0.0]
    when tail; [1.0, -1.0]
    else       [0.5, -0.5]
    end
  end
end

y_t, y_s = vector(pos, align, "top", "bottom")
x_t, x_s = vector(pos, align, "left", "right")
s.y = t.y + y_t*t.height + y_s*s.height
s.x = t.x + x_t*t.width + x_s*s.width

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM