[英]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.