I am implementing a program to draw a box of text next to some other drawn object (that can have any position and dimensions) and the text box should always be visible, even if the drawn object's width is of the entire screen and vice versa. They should simply not overlap.
This is a code to position the text on some relatively good coordinates.
if(x > (box_w + 20)) box_x = x - (box_w + 20);
else box_x = w + 20;
if(y > (box_h + 20)) box_y = y - (box_h + 20);
else box_y = h + 20;
if(w > width - (box_h + 20) || x + w + box_w + 20 > width)
{
box_x = 20;
if(y < box_h + 20)
{
box_y = h + 20;
}
else box_y = y - (box_h + 20);
}
x
, y
, w
, h
are the coords and dimensions for the object; box_x
, box_y
, box_w
and box_y
are for the text box and width/height is the dimension of the area.
Here is schematically how this code positions text (darker blue) near the object (lighter blue)
It is quite obvious that it could have been written much better. To target performance, but more importantly - code space.
Can anyone suggest a better way to find good coordinates for the text box?