# Check if rectangle sides overlap each other in 2d

I am drawing a rectangle. On touching the corners, I am able to resize this rectangle. Now, the issue is during resizing, opposite sides overlap and cross each other. I have to stop this overlapping and crossing of sides. The minimum width and height should be any fixed constant (let's say 10).

In below code left, top has cornerId 0 and left, bottom has cornerId 1 and so on. Also left, top and right, bottom makes groupId 1 and other two sides make groupId 2. Here cornerList contains the info about all the 4 coordinates.

Any help or reference is greatly appreciated. Thanks.

Reference for resizable rectangle is How to create a resizable rectangle with user touch events on Android?

private void moveCorners(float x, float y) {

cornerList.get(cornerId).setX(x);
cornerList.get(cornerId).setY(y);
paint.setColor(Color.CYAN);

if (groupId == 1) {
cornerList.get(1).setX(cornerList.get(0).getX());
cornerList.get(1).setY(cornerList.get(2).getY());
cornerList.get(3).setX(cornerList.get(2).getX());
cornerList.get(3).setY(cornerList.get(0).getY());
} else {
cornerList.get(0).setX(cornerList.get(1).getX());
cornerList.get(0).setY(cornerList.get(3).getY());
cornerList.get(2).setX(cornerList.get(3).getX());
cornerList.get(2).setY(cornerList.get(1).getY());
}

invalidate();

}


You don't need a corner list. What you need is a side list, since you are actually dragging sides - two adjacent corners always have either the same x or the same y, so corner drag is pointless.

You do need a min and max for each axis, and a minimum size:

float xMin;
float xMax;
float xMinSize;


You do need to write a getter method for width:

float getXSize()
{
return xMax - xMin; //this means your rightmost x for the rectangle, minus leftmost
}


When you drag (each frame), you must check if size is less than minimum and if it has become less, then clamp it, i.e. do not let it go below that minimum:

if (getXSize() < xMinSize)
{
//PSEUDOCODE:
//if currently dragged side is the right hand side (x max):
xCurrentlyDraggedSide = xOtherSide + minWidth;
//else if it's the left hand side (x min):
xCurrentlyDraggedSide = xOtherSide - minWidth;
}


Then do similar for y, in all the same places.

Get this working, then build your draggable corners back in ON TOP of this, if you want them.

• Thanks for the answer. Your logic seems relevant. I will get back to you once I implement it. Jul 21 '17 at 2:56
• @Tauqir Did this answer end up solving your problem? If so, don't forget to mark it as accepted - it helps others who may run into the same or similar problems. Aug 21 '18 at 14:20
• @Pikalek, this answer helped me in implementing my own logic. This answer is not complete. Aug 23 '18 at 4:48
• @Tauqir Glad to hear that it helped & you found a solution. Please consider posting (and accepting!) your own answer to help out others. Aug 23 '18 at 13:49